Black Screen when using Tiled in LibGDX - java

For the game I'm making I use Tiled to make and edit maps. However, these maps don't load in the sample I've made so far:
package com.bluezamx.magillion.screens;
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.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.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FillViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.bluezamx.magillion.Magillion;
import com.bluezamx.magillion.utils.Constants;
public class WorldScreen implements Screen {
private Magillion game;
private OrthographicCamera gameCam;
private Viewport gamePort;
private Stage stage;
//Tiled variables
private TmxMapLoader mapLoader;
private TiledMap map;
private OrthogonalTiledMapRenderer maprenderer;
// Box2D variables
private World world;
private Box2DDebugRenderer debug;
public WorldScreen (Magillion game) {
this.game = game;
gameCam = new OrthographicCamera();
mapLoader = new TmxMapLoader();
map = mapLoader.load("TestWorld.tmx");
maprenderer = new OrthogonalTiledMapRenderer(map, 1 / Constants.PPM);
gamePort = new FillViewport(Constants.WIDTH / Constants.PPM, Constants.HEIGHT / Constants.PPM, gameCam);
gameCam.position.set((gamePort.getWorldWidth() / 2), (gamePort.getWorldHeight() / 2), 0);
world = new World(new Vector2(0,0), true);
debug = new Box2DDebugRenderer();
debug.SHAPE_STATIC.set(1, 0, 0, 1);
for(MapObject object : map.getLayers().get(1).getObjects().getByType(RectangleMapObject.class)) {
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bdef.type = BodyDef.BodyType.StaticBody;
bdef.position.set(rect.getX() + rect.getWidth() / 2, rect.getY() + rect.getHeight() / 2);
body = world.createBody(bdef);
shape.setAsBox(rect.getWidth() / 2, rect.getHeight() / 2);
fdef.shape = shape;
body.createFixture(fdef);
}
}
#Override
public void show() {}
private void update(float dt) {
handleInput(dt);
world.step(1/60f, 6, 2);
player.update(dt);
gameCam.update();
maprenderer.setView(gameCam);
}
#Override
public void render(float dt) {
update(dt);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
debug.render(world, gameCam.combined);
game.batch.setProjectionMatrix(gameCam.combined);
maprenderer.render();
game.batch.begin();
player.draw(game.batch);
game.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() {
map.dispose();
maprenderer.dispose();
world.dispose();
debug.dispose();
}
}
When I run my file (which automatically sets the game screen to this file), I only get a black screen. The map itself doesn't show. The map is 640 * 480 big and placed in the standard android/assets folder.
I tried running my map in other code I found online and it worked there. I couldn't figure out what's wrong with mine, however.

You need to update your viewport with device screen width and height.
#Override
public void resize(int width, int height) {
// use true here to center the camera
gamePort.update(width,height,false);
}
Take a look of this answer, recently I added as solution.

It seems like your map is actually rendered, but simply your Viewport is out of map position.
Try using:
gamecam.setToOrtho(false, gamePort.getWorldWidth()/2, gamePort.getWorldHeight()/2);
instead of
gameCam.position.set((gamePort.getWorldWidth() / 2), (gamePort.getWorldHeight() / 2), 0);

Related

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

2 Borders of Screen Flickers

Im trying to make a simple game in LibGdx, using Tiled MapEditor and I have a little problem with rendering, left and bottom borders flickers whenever i move a camera.
Pic Related: https://gyazo.com/63b9e364cd4b2e8154c1bd177c9ee990
MyGdxGame.java
package com.mygdx.game;
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.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
public class MyGdxGame extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
AssetLoad load;
Player player;
TiledMapRenderer tiledMapRenderer;
TiledMap tiledMap;
float unitScale = 1 / 32f;
#Override
public void create () {
load = new AssetLoad();
load.manager.finishLoading();
if(load.manager.update()){
batch = new SpriteBatch();
player = new Player();
tiledMap = new TmxMapLoader().load("tilemaps/321.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap,unitScale);
batch.setProjectionMatrix(player.cam.combined);
}
}
#Override
public void render () {
update();
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
tiledMapRenderer.setView(player.cam);
tiledMapRenderer.render();
batch.end();
}
public void update(){
player.playerMove();
player.cam.update();
player.cam.position.set(player.x,player.y,0);
}
public void dispose(){
}
Player.java
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.OrthographicCamera;
public class Player {
public OrthographicCamera cam = new OrthographicCamera(1024,720);
int x = 10;
int y = 12;
public Player(){
cam.setToOrtho(false,30,20);
}
public void playerMove()
{
if(Gdx.input.isKeyPressed(Keys.W))
{
y += 1;
}
if(Gdx.input.isKeyPressed(Keys.A))
{
x -= 1;
}
if(Gdx.input.isKeyPressed(Keys.S))
{
y -= 1;
}
if(Gdx.input.isKeyPressed(Keys.D))
{
x += 1;
}
}
}
You update the cam before your set it's position rather than after, and the projection matrix is never updated. Hopefully these two things fix your problem.
public void update(){
player.playerMove();
player.cam.update();
player.cam.position.set(player.x,player.y,0);
}
should be
public void update(){
player.playerMove();
player.cam.position.set(player.x,player.y,0);
player.cam.update();
batch.setProjectionMatrix(player.cam.combined);
}

Error:(11, 24) error: package javafx.animation does not exist. (Android Studio, Libgdx, Javafx)

I am trying to create a Space Shooter game using LibGDX in Android Studio.
Everything else was working fine until I tried to create animation using javafx.animation.Animation class. While compiling my code, I get the following 3 errors and 1 warning !
Warning:[options] bootstrap class path not set in conjunction with -source 1.6
Error:(11, 24) error: package javafx.animation does not exist
Error:(22, 13) error: cannot find symbol class Animation
Error:(44, 26) error: cannot find symbol class Animation
I have checked that my android studio does have a plugin for javafx !
I have two classes in my code Shootergame.java and AnimatedSprite.java
The problem lies in AnimatedSprite.java class and the code for that class is below !
package com.ahmed.nullapointershooter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import javafx.animation.Animation;
/**
* Created by Hafeez ur Rehman on 8/30/2015.
**/
public class AnimatedSprite {
private static final int FRAMES_COL = 2;
private static final int FRAMES_ROW = 2;
private Sprite sprite;
private Animation animation;
private TextureRegion[] frames;
private TextureRegion currentFrame;
private float stateTime;
public AnimatedSprite(Sprite sprite) {
this.sprite = sprite;
Texture texture = sprite.getTexture();
TextureRegion[][] temp = TextureRegion.split(texture, texture.getWidth() / FRAMES_COL,
texture.getHeight() / FRAMES_ROW);
frames = new TextureRegion[FRAMES_COL * FRAMES_ROW];
int index = 0;
for (int i = 0; i < FRAMES_ROW; i++) {
for (int j = 0; j < FRAMES_COL; j++) {
frames[index++] = temp[i][j];
}
}
/**
* THE PROBLEM LIES HERE . I WANT TO DO THIS ----
*
*/
//animation = new Animation(0.1f, frames);
animation = new Animation() {
#Override
public void impl_playTo(long l, long l1) {
}
#Override
public void impl_jumpTo(long l, long l1) {
}
};
stateTime = 0f;
}
public void setPosition(float x, float y){
float widthOffset = sprite.getWidth() / FRAMES_COL;
sprite.setPosition(x - widthOffset / 2, y);
}
public void draw(SpriteBatch spriteBatch){
stateTime += Gdx.graphics.getDeltaTime();
//currentFrame = animation.getKeyFrame(stateTime, true);
spriteBatch.draw(currentFrame, sprite.getX(), sprite.getY());
}
}
and also code for Shootergame.java just for reference for what I am doing!
package com.ahmed.nullapointershooter;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class ShooterGame extends ApplicationAdapter {
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture background;
private AnimatedSprite spaceshipAnimated;
#Override
public void create() {
//Texture.setEnforcePotImages(false);
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
batch = new SpriteBatch();
background = new Texture(Gdx.files.internal("NullapointerBackground.png"));
Texture spaceshipTexture = new Texture(Gdx.files.internal("Spaceshipcanvas.png"));
Sprite spaceshipSprite = new Sprite(spaceshipTexture);
spaceshipAnimated = new AnimatedSprite(spaceshipSprite);
spaceshipAnimated.setPosition(800 / 2, 0);
}
#Override
public void dispose() {
batch.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, 0, 0);
spaceshipAnimated.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
}
My problem solved . I was using Javafx to import animation class which was wrong at the first place because there is no javafx package in android. Instead I had to import
import com.badlogic.gdx.graphics.g2d.Animation; Now its working !

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

Categories