libgdx background image not displaying - java

I have in the constructor:
backgroundTexture = new Texture(Gdx.files.internal("Pantalla.jpg"));
And in the render():
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
myGame.batch.setProjectionMatrix(camera.combined);
myGame.batch.begin();
myGame.batch.draw(backgroundTexture, 0, 0);
stage.draw();
myGame.batch.end();
}
The full code of the class is:
package states;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import mx.itesm.mty.MyGame;
public class MenuState implements Screen{
final MyGame myGame;
Skin skin;
Skin skinPant;
Stage stage;
SpriteBatch batch;
TextButton.TextButtonStyle textButtonStyle1;
TextButton.TextButtonStyle textButtonStyle2;
TextButton.TextButtonStyle textButtonStyle3;
TextButton.TextButtonStyle textButtonStyle4;
TextureAtlas buttonAtlas;
BitmapFont font;
Texture backgroundTexture;
Sprite backgroundSprite;
OrthographicCamera camera;
public MenuState(final MyGame game) {
myGame = game;
camera = new OrthographicCamera();
camera.setToOrtho(false,800,480);
batch = new SpriteBatch();
skin = new Skin();
font = new BitmapFont();
stage = new Stage();
Gdx.input.setInputProcessor(stage);
buttonAtlas = new TextureAtlas(Gdx.files.internal("boton.atlas"));
skin.addRegions(buttonAtlas);
backgroundTexture = new Texture(Gdx.files.internal("Pantalla.jpg"));
backgroundSprite = new Sprite(backgroundTexture);
textButtonStyle1 = new TextButton.TextButtonStyle();
textButtonStyle1.font = font;
textButtonStyle1.down = skin.getDrawable("Inicio");
textButtonStyle1.up = skin.getDrawable("Inicio");
textButtonStyle1.checked = skin.getDrawable("Inicio");
TextButton buttonPlay = new TextButton("", textButtonStyle1);
textButtonStyle2 = new TextButton.TextButtonStyle();
textButtonStyle2.font = font;
textButtonStyle2.down = skin.getDrawable("Instrucciones");
textButtonStyle2.up = skin.getDrawable("Instrucciones");
textButtonStyle2.checked = skin.getDrawable("Instrucciones");
TextButton buttonInst = new TextButton("",textButtonStyle2);
textButtonStyle3 = new TextButton.TextButtonStyle();
textButtonStyle3.font = font;
textButtonStyle3.down = skin.getDrawable("Informacion");
textButtonStyle3.up = skin.getDrawable("Informacion");
textButtonStyle3.checked = skin.getDrawable("Informacion");
TextButton buttonInfo = new TextButton("",textButtonStyle3);
textButtonStyle4 = new TextButton.TextButtonStyle();
textButtonStyle4.font = font;
textButtonStyle4.down = skin.getDrawable("Salir");
textButtonStyle4.up = skin.getDrawable("Salir");
textButtonStyle4.checked = skin.getDrawable("Salir");
TextButton buttonSalir = new TextButton("",textButtonStyle4);
buttonPlay.setWidth(300f);
buttonPlay.setHeight(100f);
buttonPlay.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2);
buttonInst.setWidth(300f);
buttonInst.setHeight(100f);
buttonInst.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2 - 120f);
buttonInfo.setWidth(300f);
buttonInfo.setHeight(100f);
buttonInfo.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2 - 240f);
buttonSalir.setWidth(300f);
buttonSalir.setHeight(100f);
buttonSalir.setPosition(Gdx.graphics.getWidth() / 2 - 150f, Gdx.graphics.getHeight() / 2 - 360f);
buttonPlay.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
buttonInst.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
buttonInfo.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
buttonSalir.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
myGame.setScreen(new PlayMenuState(myGame));
}
});
stage.addActor(buttonPlay);
stage.addActor(buttonInst);
stage.addActor(buttonInfo);
stage.addActor(buttonSalir);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
myGame.batch.setProjectionMatrix(camera.combined);
myGame.batch.begin();
myGame.batch.draw(backgroundTexture, 0, 0);
stage.draw();
myGame.batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
I add several buttons and the background image. The image is in the assets folder but it juts doesn't show up.
And I had a doubt about rectangles that if there is a way to add an image to a Rectangle object the same way you set the x, y, height, width?

A Stage has it's own batch which will call begin() and end(), unless you specifically set the stage to use the same batch, the begin() and end() calls will conflict.
However you also might want to clean up your code, because you create a background sprite but not use it. I would recommend using this in stead of directly drawing the texture though (because a sprite can also have a position and other attributes which you can manipulate).

Related

Libgdx the correct way to make a game

Recently I started making my "first" real RPG (The other 'RPG's' were text based in batch or whatever). I am using Libgdx, since from what I read it's pretty simple to get the hang of.
But what I'm interested in is am I doing it right?
For example I make a TiledMap and draw the camera etc. everything 'semi works', but is it right? On one tutorial there was a person which created thread's and much more, so it's making me think I'm doing it wrong
For example this is my GameScreen
public class GameScreen implements Screen, Runnable{
private MenuScreen menuScreen;
SpriteBatch batch, infobatch;
BitmapFont font;
private int tileWidth, tileHeight,
mapWidthInTiles, mapHeightInTiles,
mapWidthInPixels, mapHeightInPixels;
private float delta;
private InputHandler inputHandler;
private TiledMap map;
private AssetManager manager;
private OrthogonalTiledMapRenderer renderer;
private OrthographicCamera camera;
private FitViewport playerViewport;
private Player player;
public GameScreen(MenuScreen mc)
{
menuScreen=mc;
}
#Override
public void show() {
batch = new SpriteBatch();
infobatch = new SpriteBatch();
font = new BitmapFont(Gdx.files.local("font/ornlan.fnt"));
font.setColor(Color.BLACK);
manager = new AssetManager();
manager.setLoader(TiledMap.class, new TmxMapLoader());
manager.load("world/test_1.tmx", TiledMap.class);
manager.finishLoading();
map = manager.get("world/test_1.tmx", TiledMap.class);
MapProperties properties = map.getProperties();
tileWidth = properties.get("tilewidth", Integer.class);
tileHeight = properties.get("tileheight", Integer.class);
mapWidthInTiles = properties.get("width", Integer.class);
mapHeightInTiles = properties.get("height", Integer.class);
mapWidthInPixels = mapWidthInTiles * tileWidth;
mapHeightInPixels = mapHeightInTiles * tileHeight;
camera = new OrthographicCamera(960.f, 720.f);
playerViewport = new FitViewport(mapWidthInTiles, mapHeightInTiles, camera);
camera.position.x = MathUtils.clamp(camera.position.x, camera.viewportWidth / 2, mapWidthInPixels - camera.viewportWidth /2);
camera.position.y = MathUtils.clamp(camera.position.y, camera.viewportHeight / 2, mapHeightInPixels - camera.viewportHeight / 2);
renderer = new OrthogonalTiledMapRenderer(map);
player = new Player();
inputHandler = new InputHandler();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0.75f, 0.75f, 0.85f, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
camera.position.set(Player.x + Player.width / 2, Player.y + Player.height / 2, 0);
camera.update();
renderer.setView(camera);
renderer.render();
infobatch.begin();
font.draw(infobatch, "Test World, Dev. purposes", 10,25);
font.draw(infobatch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 1180, 700);
infobatch.end();
batch.begin();
batch.setProjectionMatrix(camera.combined);
delta = Gdx.graphics.getDeltaTime();
inputHandler.update();
player.update(delta);
player.render(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
batch.dispose();
infobatch.dispose();
font.dispose();
renderer.dispose();
manager.dispose();
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
And this is my "MainMenu"
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
public class MenuScreen extends Game {
SpriteBatch batch;
BitmapFont font;
private Stage stage;
private GameScreen gameScreen;
private Texture btn_start;
private TextureRegion btn_startRegion;
private TextureRegionDrawable btn_startDrawable;
private ImageButton btn_startIB;
#Override
public void create() {
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.local("font/ornlan.fnt"));
font.setColor(Color.BLACK);
btn_start = new Texture(Gdx.files.internal("ui/start_btn.png"));
btn_startRegion = new TextureRegion(btn_start);
btn_startDrawable = new TextureRegionDrawable(btn_startRegion);
btn_startIB = new ImageButton(btn_startDrawable);
btn_startIB.setPosition(10, 250);
stage = new Stage(new ScreenViewport());
stage.addActor(btn_startIB);
Gdx.input.setInputProcessor(stage);
btn_startIB.addCaptureListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
try {
System.out.println("Starting GameScreen...");
setGameScreen();
} catch (Exception e) {
System.out.println("Error starting GameScreen E:" + e);
}
};
});
}
#Override
public void render() {
Gdx.gl.glClearColor(0.67f, 0.75f, 0.98f, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
batch.begin();
font.getData().setScale(0.8f,0.8f);
font.draw(batch, "Ornlan DevBuild (pa) v0.0.0.1", 1000, 25);
batch.end();
stage.act(Gdx.graphics.getDeltaTime()); // Perform ui logic
stage.draw();
super.render();
}
#Override
public void dispose() {
batch.dispose();
font.dispose();
super.dispose();
}
void setGameScreen() {
gameScreen = new GameScreen(this);
setScreen(gameScreen);
}
}

Box2d collision wont run on collision

Contact Collision box2D wont run on collision i want the bullet to be able to run the WorldContactListener beginContact when it begins contact and when it ends contact runningendContact
iv'e looked through a lot of places and i cant get a system print
This is my contact listener class:
package com.mygdx.game;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
public class WorldContactListener implements ContactListener {
#Override
public void beginContact(Contact contact) {
//called when 2 fixtures collide
System.out.println("Begin Contact");
}
#Override
public void endContact(Contact contact) {
//called when the 2 fixtures connected gets split apart
System.out.println("end Contact");
}
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
//gives power to change the characteristics of fixture
collision
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
//gives results of what happened because of collision like
angles ext
}
}
play screen class:
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.game.Sprites.Bullet;
import com.mygdx.game.Sprites.InversePlayer;
import com.mygdx.game.Sprites.Player;
#SuppressWarnings("unused")
public class PlayScreen implements Screen {
private main game;
private TextureAtlas atlas;
private OrthographicCamera gamecam;
private Viewport gamePort;
private Hud hud;
private TmxMapLoader maploader;
private TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private World world;
private Box2DDebugRenderer b2dr;
private Player player;
private InversePlayer inversePlayer;
private Bullet bullet;
public PlayScreen(main game) {
atlas = new TextureAtlas("BurningShooterPlayer.pack");
this.game = game;
gamecam = new OrthographicCamera();
gamePort = new FitViewport(main.V_WIDTH / main.PPM, main.V_HEIGHT / main.PPM, gamecam);
hud = new Hud(game.batch);
maploader = new TmxMapLoader();
map = maploader.load("map1.tmx");
renderer = new OrthogonalTiledMapRenderer(map, 1 / main.PPM);
gamecam.position.set(gamePort.getWorldWidth()/2, gamePort.getWorldHeight()/2, 0);
world = new World(new Vector2(0,-10), true);
b2dr = new Box2DDebugRenderer();
new B2WorldCreator(this);
player = new Player(this);
inversePlayer = new InversePlayer(this, .32f, .32f);
bullet = new Bullet(this, .64f, .64f);
}
public TextureAtlas getAtlas() {
return atlas;
}
#Override
public void show() {
//world.setContactListener(ContactListener listener) .
}
public void handleInput(float dt) {
if(Gdx.input.isKeyJustPressed(Input.Keys.W))
player.b2body.applyLinearImpulse(new Vector2(0, 4f), player.b2body.getWorldCenter(), true);
if(Gdx.input.isKeyPressed(Input.Keys.D) && player.b2body.getLinearVelocity().x <= 2)
player.b2body.applyLinearImpulse(new Vector2(0.1f , 0), player.b2body.getWorldCenter(), true);
if(Gdx.input.isKeyPressed(Input.Keys.A) && player.b2body.getLinearVelocity().x >= -2)
player.b2body.applyLinearImpulse(new Vector2(-0.1f , 0), player.b2body.getWorldCenter(), true);
if(Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)) {
bullet.b2body.setLinearVelocity(0, 0);
bullet.b2body.setTransform(new Vector2((float)(player.b2body.getPosition().x+player.getWidth()-(3/main.PPM)), (float)(player.b2body.getPosition().y)), 0);
bullet.b2body.applyLinearImpulse(new Vector2(Bullet.BULLET_SPEED, 0), bullet.b2body.getWorldCenter(), true);
Bullet.Right = true;
}
if(Gdx.input.isKeyJustPressed(Input.Keys.LEFT)) {
bullet.b2body.setLinearVelocity(0, 0);
bullet.b2body.setTransform(new Vector2((float)(player.b2body.getPosition().x-player.getWidth()+(3/main.PPM)), (float)(player.b2body.getPosition().y)), 0);
bullet.b2body.applyLinearImpulse(new Vector2(-Bullet.BULLET_SPEED, 0), bullet.b2body.getWorldCenter(), true);
Bullet.Right = false;
}
//if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
//bullet.b2body.setBullet(true);
//world.destroyBody(bullet.b2body);
//}
}
public void update(float dt) {
handleInput(dt);
world.step(1/60f, 6, 2);
player.update(dt);
inversePlayer.update(dt);
bullet.update(dt);
gamecam.position.x = player.b2body.getPosition().x;
gamecam.update();
renderer.setView(gamecam);
}
#Override
public void render(float delta) {
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderer.render();
b2dr.render(world, gamecam.combined);
game.batch.setProjectionMatrix(gamecam.combined);
game.batch.begin();
player.draw(game.batch);
inversePlayer.draw(game.batch);
bullet.draw(game.batch);
game.batch.end();
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
}
#Override
public void resize(int width, int height) {
gamePort.update(width, width);
}
public TiledMap getMap() {
return map;
}
public World getWorld() {
return world;
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
world.dispose();
b2dr.dispose();
hud.dispose();
}
}
Bullet code (i want to detect if it collides with another body):
package com.mygdx.game.Sprites;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.utils.Array;
import com.mygdx.game.PlayScreen;
import com.mygdx.game.main;
public class Bullet extends projectile{
private float stateTime;
private Animation<TextureRegion> walkAnimation;
private Array<TextureRegion> frames;
public static float BULLET_SPEED = 1f;
public static boolean Right = true;
public Bullet(PlayScreen screen, float x, float y) {
super(screen, x, y);
frames = new Array<TextureRegion>();
frames.add(new TextureRegion(screen.getAtlas().findRegion("BurningShooterPlayer"),111, -1, 15, 8));
walkAnimation = new Animation<TextureRegion>(0.1f, frames);
stateTime = 0;
setBounds(getX(), getY(), (float) (7.5/ main.PPM), 4 / main.PPM);
}
public void update(float dt) {
stateTime += dt;
setPosition((b2body.getPosition().x - getWidth() / 2), b2body.getPosition().y - getHeight() / 2);
setRegion(walkAnimation.getKeyFrame(stateTime, true));
if((!Right) && !walkAnimation.getKeyFrame(dt).isFlipX()) {
walkAnimation.getKeyFrame(dt).flip(true, false);
}
else if((Right) && walkAnimation.getKeyFrame(dt).isFlipX()) {
walkAnimation.getKeyFrame(dt).flip(true, false);
}
}
#Override
protected void defineProjectile() {
BodyDef bdef = new BodyDef();
bdef.position.set(64 / main.PPM, 64 / main.PPM);
bdef.type = BodyDef.BodyType.DynamicBody;
b2body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox((float) (7.5 / 2 / main.PPM), 4 / 2 / main.PPM);
fdef.filter.categoryBits = main.ENEMY_BIT;
fdef.filter.maskBits = main.GROUND_BIT |
main.ENEMY_BIT |
main.OBJECT_BIT;
fdef.shape = shape;
fdef.density = 100;
b2body.setBullet(true);
b2body.createFixture(fdef);
b2body.setUserData(this);
}
}
You create the World but you forget to set your ContactListener to your world:
private World world;
private WorldContactListener worldContactListener;
public PlayScreen(main game) {
...
world = new World(new Vector2(0,-10), true);
worldContactListener = new WorldContactListener();
world.setContactListener(worldContactListener);
...
}

Libgdx & Android Studio: Label doesn't show any text

I am trying to add a Label text to the screen but nothing seems to be showing up: This is the code that I have coded and below has the screen that I ended up with, I could still change all colours but nothing shows up
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.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
public class FiraMain extends ApplicationAdapter {
SpriteBatch batch;
private Skin mySkin;
private Stage stage;
#Override
public void create () {
batch = new SpriteBatch();
stage = new Stage(new ScreenViewport());
int guides = 12;
int rowHeight = Gdx.graphics.getWidth() / 12;
int colWidth = Gdx.graphics.getHeight() / 12;
Label.LabelStyle labelStyle = new Label.LabelStyle();
Skin mySkin = new Skin(Gdx.files.internal("skin/glassy-ui.json"));
Label label = new Label("Text", mySkin);
label.setSize(Gdx.graphics.getWidth() / guides, rowHeight);
label.setPosition(colWidth * 2, Gdx.graphics.getHeight() - rowHeight * 6);
stage.addActor(label);
}
#Override
public void render () {
Gdx.gl.glClearColor(1, 1, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.end();
}
#Override
public void dispose () {
}
}
Image
I think by mistake you forgot to call draw method of stage.
#Override
public void render () {
Gdx.gl.glClearColor(1, 1, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw(); //<-- Call draw method of stage inside render, it calls draw on every actor in the stage
stage.act();
}
Also I like to recommend you to dispose all disposable element in your game.
#Override
public void dispose () {
stage.dispose();
mySkin.dispose();
batch.dispose();
}

libGDX textures are "stretched"

I am currently working with libGDX and got to a strange problem.
The textures that I use with batch and rectangles are stretched. Here is a picture.
As you can see, the background looks completely normal, but the person in the middle is a lot taller than the person in the left corner, which it should look like.
Here is my code:
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Array;
import com.data.Manager;
public class GameScreen implements Screen{
private Texture backgroundTexture = Manager.manager.get(("Ressources/Hintergrund_Skizze.png"), Texture.class);
private Texture farmerBackTexture = Manager.manager.get(("Ressources/Farmer_Back_Skizze.png"), Texture.class);
private Texture farmerRightTexture = Manager.manager.get(("Ressources/Farmer_Right_Skizze.png"), Texture.class);
private Texture farmerLeftTexture = Manager.manager.get(("Ressources/Farmer_Left_Skizze.png"), Texture.class);
private Texture ufoTexture = Manager.manager.get(("Ressources/Ufo_Skizze.png"), Texture.class);
private Texture laserTexture = Manager.manager.get(("Ressources/Magic_Ball.png"), Texture.class);
private Image backgroundImage = new Image(backgroundTexture);
private Image farmerBackImage = new Image(farmerBackTexture);
private Stage levelStage = new Stage(), menuStage = new Stage();
private Table menuTable = new Table();
private Skin menuSkin = Manager.menuSkin;
private OrthographicCamera camera;
private SpriteBatch batch;
private Rectangle farmer, ufo;
private Array<Rectangle> lasers;
private boolean ufoMovementLeft = true;
private boolean leftArrow = false;
private boolean rightArrow = false;
private float laserMovement = 0;
private int ufoLife = 15;
#Override
public void show() {
levelStage.addActor(backgroundImage);
levelStage.addActor(farmerBackImage);
Gdx.input.setInputProcessor(levelStage);
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
farmer = new Rectangle();
farmer.x = 800 / 2 - 80 / 2; farmer.y = 80;
farmer.width = 80; farmer.height = 270;
ufo = new Rectangle();
ufo.x = 800 / 2; ufo.y = 375;
ufo.width = 185; ufo.height = 94;
lasers = new Array<Rectangle>();
}
public void movement() {
if(Gdx.input.isKeyPressed(Keys.LEFT)) leftArrow = true;
if(!Gdx.input.isKeyPressed(Keys.LEFT)) leftArrow = false;
if(Gdx.input.isKeyPressed(Keys.RIGHT)) rightArrow = true;
if(!Gdx.input.isKeyPressed(Keys.RIGHT)) rightArrow = false;
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
levelStage.act();
levelStage.draw();
batch.setProjectionMatrix(camera.combined);
batch.begin();
movement();
if(leftArrow) {if(farmer.x >= 60) farmer.x -= 2; batch.draw(farmerLeftTexture, farmer.x, farmer.y);}
else if(rightArrow) {if(farmer.x <= 590) farmer.x += 2; batch.draw(farmerRightTexture, farmer.x, farmer.y);}
else batch.draw(farmerBackTexture, farmer.x, farmer.y);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
levelStage.dispose(); menuStage.dispose();
menuSkin.dispose();
ufoTexture.dispose();
laserTexture.dispose();
farmerBackTexture.dispose();
farmerRightTexture.dispose();
farmerLeftTexture.dispose();
}}
I hope you are able to help me find the mistake.
Cheers,
Joshflux
EDIT: I am pretty sure, that it has to do something with the size of the window. If I resize the height of the window from 800 to 200, the person in the left corner looks the same, but the person in the middle is way smaller. Still can't figure out how to solve it though...
The problem is that your levelStage uses a different camera.
new Stage();
Creates a stage with its own camera and a scaling viewport. And here you create another camera:
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
Note that this does NOT set the window size!
With a static size, as you never update it when you resize the window.
Since you use a stage for your level you could do this:
batch.setProjectionMatrix(levelStage.getCamera().combined);
If you don't want a scaling viewport create your own (take a look a the different viewports) and add it as an parameter to new Stage(viewport).
To set the window size you need to go to the desktop project and change it in the config class.
That happens because you are adding an actor to a scene and just drawing an texture after. you could use some information about differences of actors and texture drawing here:
libgdx difference between sprite and actor
When to use actors in libgdx? What are cons and pros?

LibGDX - How to clear the Screen

I'm trying to display 2 different screens, changing when the user touches the screen. So far with the code below the screens change but the text just keeps overlapping and piling up. I need to dispose of EVERYTHING on the screen before switching.
One of the 2 similar pages(only the text is different on the 2)
package com.me.mygdxgame;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
public class MainMenu implements Screen {
OrthographicCamera camera;
SpriteBatch batch;
Screens game;
BitmapFont font;
public MainMenu(Screens game) {
this.game = game;
}
#Override
public void dispose() {
batch.dispose();
font.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void render(float delta) {
CharSequence str = "Main Menu";
batch = new SpriteBatch();
font = new BitmapFont();
batch.begin();
font.draw(batch, str, 200, 200);
batch.end();
if (Gdx.input.justTouched()) // use your own criterion here
game.setScreen(game.anotherScreen);
}
#Override
public void show() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
}
Screens.java
package com.me.mygdxgame;
import com.badlogic.gdx.Game;
public class Screens extends Game {
MainMenu mainMenuScreen;
AnotherScreen anotherScreen;
#Override
public void create() {
mainMenuScreen = new MainMenu(this);
anotherScreen = new AnotherScreen(this);
setScreen(mainMenuScreen);
}
}
Change your render function to:
#Override
public void render(float delta) {
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); //clears the buffer
CharSequence str = "Main Menu";
batch = new SpriteBatch();
font = new BitmapFont();
batch.begin();
font.draw(batch, str, 200, 200);
batch.end();
if (Gdx.input.justTouched()) // use your own criterion here
game.setScreen(game.anotherScreen);
}

Categories