Libgdx the correct way to make a game - java

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);
}
}

Related

Why is my create() Method Not Recognizing a Global Variable? - Java LibGDX

I have global variables called:
private int currentLevel;
private int mapHeight;
I have a constructor for my game, where currentLevel = level entered when setScreen() method is called:
public ElevatorLevel(Game g, int level)
{
super(g, level);
currentLevel = level;
}
In my create() method, I set mapHeight to 750 * currentLevel (which starts as one), however when I try to spawn in the blades as seen below, they spawn between -200 and 300. This is because the program is not recognizing currentLevel (I am assuming), so it is multiplying it by nothing, resulting with -200.
public void create()
{
world = new World(new Vector2(0, -9.8f), true);
timeElapsed = 0;
mapHeight = 750 * currentLevel;
blade = new PhysicsActor();
blade.storeAnimation( "", exTex );
blade.setOriginCenter();
blade.circularBoundary();
blade.setMaxSpeed(50);
blade.setDeceleration(50);
bladesList = new ArrayList<PhysicsActor>();
for (int i = 0; i < 3 ; i++)
{
blades = blade.clone();
float xCoord = randomFloatGenerator(440, 20);
float yCoord = randomFloatGenerator(mapHeight - 200, 300);
blades.setPosition(xCoord, yCoord);
mainStage.addActor(blades);
bladesList.add(blades);
}
I also have a Label in my update(float dt) method that is set to:
timeLabel.setText("Level: " + currentLevel);
As seen in the image above, currentLevel is recognized by the label, but not by mapHeight in create().
How do I get currentLevel to be recognized by the create() method?
Below is the standart portrait app code that i use almost in every libgdx project. I never use create method. Instead I use constructor, this code is the most bugfree one that i could have found.
GAME OR MENU SCREEN:
public class TutorialScreen implements Screen {
private OrthographicCamera camera;
public static final float WORLD_HEIGHT = 240;
public static final float WORLD_WIDTH = 135;
private Viewport viewport;
private Stage stage;
private EntryPoint game;
private AdsController adsController;
public TutorialScreen(final EntryPoint game, final AdsController adsController){
this.adsController = adsController;
this.game = game;
adsController.hideBannerAd();
float aspectRatio = (float) (Gdx.graphics.getHeight() / Gdx.graphics.getWidth());
camera = new OrthographicCamera(aspectRatio * WORLD_WIDTH, WORLD_HEIGHT);
camera.setToOrtho(false);
viewport = new FitViewport(WORLD_WIDTH , WORLD_HEIGHT,camera );
stage = new Stage(viewport, game.batch);
}
#Override
public void show() {
}
#Override
public void render(float delta) {
stage.draw();
stage.act();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
ENTRY POINT THAT YOUR APP WILL OPEN FIRST:
package some.package;
public class EntryPoint extends Game {
SpriteBatch batch;
final AdsController adsController;
public EntryPoint(final AdsController adsController ){
this.adsController = adsController; //Interface for admob
}
#Override
public void create () {
batch = new SpriteBatch();
this.setScreen(new YourScreenClass(this,adsController)); //Above is tutorial so this would be new TutorialScreen(this,adsController)
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.end();
super.render();
}
#Override
public void dispose () {
batch.dispose();
}
}
Might have missed some curly brackets or ";" but you get the idea. This way you would not encounter any reference issues.

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 background image not displaying

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).

Stage and Box2d cameras are not aligned

In my first game I used Scened2d + Box2d rendering my bodies independently without extending Actor. It works, but it is messy and not recommended.
Now in my second game, I would like to do it properly and create a bridge between Scened2d and Box2d by using a physics stage Stage.
I found this code http://pastebin.com/rNpxvT80 what does pretty much what I need. However, the stage and box2d cameras are not aligned even if used mDebugRenderer.render(world, camera.combined) in the Draw() method of my Stage class called GameStage.
I have taken a look on this, but I had no luck libGdx How to use images or actor as body.
I know it may be something simple, but is wrecking my head...
Here is the result:
Here is the full "working" source code:
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
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.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
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.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
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.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class Box2D_Platformer extends Game {
public World mBoxWorld;
public Box2DDebugRenderer mDebugRenderer;
public OrthographicCamera mCam;
public AssetManager mManager;
public sprite_actor mBall;
public GameStage stage;
public SpriteBatch batch;
public static final float PIXEL_TO_METER_RATIO_DEFAULT = 32f;
static final float one_over_60 = 1f / 60f;
#Override
public void create() {
init();
batch = new SpriteBatch();
stage = new GameStage();
Gdx.input.setInputProcessor(stage);
stage.setupStage(mCam, mBoxWorld, mDebugRenderer);
stage.addActor(mBall);
}
#Override
public void render() {
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
render_physics();
stage.draw();
}
#Override
public void dispose() {
stage.dispose();
mManager.dispose();
}
private void init() {
mManager = new AssetManager();
mCam = new OrthographicCamera(1024, 768);
mCam.update();
init_physics();
init_ball();
}
private void init_physics() {
mBoxWorld = new World(new Vector2(0, -200), true);
mDebugRenderer = new Box2DDebugRenderer();
create_static_object_floor();
}
private void init_ball() {
TextureAtlas atlasSprites;
mManager.load("data/atlas.txt",TextureAtlas.class);
mManager.finishLoading();
atlasSprites = mManager.get("data/atlas.txt");
TextureRegion t = atlasSprites.findRegion("bar");
//
mBall = new sprite_actor(mBoxWorld, new Sprite(t));
}
private Body create_dynamic_object_ball() {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(100 / PIXEL_TO_METER_RATIO_DEFAULT,5000 / PIXEL_TO_METER_RATIO_DEFAULT );
Body body = mBoxWorld.createBody(bodyDef);
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(1f*PIXEL_TO_METER_RATIO_DEFAULT);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 1f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = body.createFixture(fixtureDef);
circle.dispose();
return body;
}
private Body create_static_object_floor() {
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(new Vector2(0, 10));
Body groundBody = mBoxWorld.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox(mCam.viewportWidth, 10.0f);
groundBody.createFixture(groundBox, 0.0f);
groundBox.dispose();
return groundBody;
}
private void render_physics() {mDebugRenderer.render(mBoxWorld, mCam.combined);}
private float to_world_x(float size) {return size /PIXEL_TO_METER_RATIO_DEFAULT;}
private float to_world_y(float size) {return size /PIXEL_TO_METER_RATIO_DEFAULT;}
private class sprite_actor extends Actor {
private Body mBody = null;
private Sprite mSprite;
public sprite_actor(World world, Sprite sprite) {
this.mSprite = sprite;
create_body();
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw(Batch batch, float parentAlpha) {
// TODO Auto-generated method stub
setRotation(MathUtils.radiansToDegrees * mBody.getAngle());
setPosition(to_world_x(mBody.getPosition().x),to_world_y(mBody.getPosition().y));
batch.draw(mSprite, getX(), getY());
System.out.println("("+to_world_x(mBody.getPosition().x)+","+to_world_y(mBody.getPosition().y)+")");
}
private void create_body() {
mBody = create_dynamic_object_ball();
}
}
private class GameStage extends Stage {
private World world;
private OrthographicCamera camera;
public void setupStage(OrthographicCamera cam, World box_world,Box2DDebugRenderer renderer) {
this.world = box_world;
this.camera = cam;
}
#Override
public void act(float step) {
world.step(one_over_60, 6, 2);
super.act(step);
}
#Override
public void draw() {
mDebugRenderer.render(world, camera.combined);
super.draw();
}
}
}

libgdx rendering srite over another causes background sprite to disapear

image of problem http://imgur.com/ZNpHiiu so I succesfully rendered a background for my game , now i tried to render some sprites on top of it and screen gets all messed up big Blue L.
code main
public class WizardGame extends Game {
public static final String TITLE = "Are you a bad enough wizard to save the princess?!", VERISION = "0.0.0.0.PREALPHA";
PlayTest pt = new PlayTest();
private FPSLogger fps;
public void create() {
Gdx.gl20.glClearColor(0, 0, 0, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
fps = new FPSLogger();
fps.log();
pt.create();
}
public void dispose() {
super.dispose();
}
public void render() {
super.render();
pt.render();
}
public void resize(int width, int height) {
super.resize(width, height);
}
public void pause() {
super.pause();
}
public void resume() {
super.resume();
}
}
playtest code
public class PlayTest implements Screen {
private TextureAtlas atlas;
private AtlasRegion floor;
private SpriteBatch batch;
private OrthographicCamera camera;
private Sprite background;
private BitmapFont font;
private String fps;
Blocks block = new Blocks();
public void render() {
Gdx.gl20.glClearColor(0, 0, 05, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
background.setBounds(0, 0, 720, 1280);
background.draw(batch);
block.renderBlocks();
batch.end();
}
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
public void show() {
}
public void hide() {
}
public void pause() {
}
public void resume() {
}
public void dispose() {
atlas.dispose();
batch.dispose();
}
public void create() {
atlas = new TextureAtlas(Gdx.files.internal("data/wizardpack.pack"));
floor = atlas.findRegion("Backfloor");
background = new Sprite(floor);
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/magicdebug48.fnt"));
block.create();
}
#Override
public void render(float delta) {
// TODO Auto-generated method stub
}
}
block code
public class Blocks extends Game {
private TextureAtlas atlas;
private SpriteBatch batch;
private AtlasRegion sword,shield,staff,fireball,iceball;
private Sprite sprSword,sprShield,sprStaff,sprFireball,sprIceball;
#Override
public void create() {
atlas = new TextureAtlas(Gdx.files.internal("data/wizardpack.pack"));
batch = new SpriteBatch();
sword = atlas.findRegion("Sword");
shield = atlas.findRegion("Shield");
staff = atlas.findRegion("Staff");
fireball = atlas.findRegion("flame");
iceball = atlas.findRegion("icespell");
sprSword = new Sprite(sword);
sprShield = new Sprite(shield);
sprStaff = new Sprite(staff);
sprFireball = new Sprite(fireball);
sprIceball = new Sprite(iceball);
}
public void renderBlocks(){
Gdx.gl20.glClearColor(0, 0, 05, 1);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(sword, 0, 0, 0, 0, 32, 32, 1, 1, 0);
//sprShield.setBounds(15, 15, 32, 32);
// sprShield.draw(batch);
batch.end();
}
public void dispose(){
atlas.dispose();
batch.dispose();
}
}
I fixed it :D the call to renderBlocks has to be after the end of batch.

Categories