I have written the following code to destroy a particular object after collision by calculating its impulse force but the game crashes whenever it tries to destroy the object showing an error :
Assertion failed: (IsLocked() == false), function DestroyBody,
file /Users/badlogic/jenkins/workspace/libgdx-mac/gdx/jni/Box2D/Dynamics/b2World.cpp, line 134.
Kindly Help. Thanks in advance.
package com.me.mygdxgame;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
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 MyGdxGame implements ApplicationListener {
private Levels level1;
private Box2DDebugRenderer renderer;
private Vector2 groundPositionLeft, groundPositionRight;
private SpriteBatch batch;
private Sprite sprite;
private boolean[] a;
private Input input;
private ContactListener conlis;
#Override
public void create() {
contactlistener();
level1 = new Levels();
renderer = new Box2DDebugRenderer();
batch = new SpriteBatch();
input = new Input() {
};
groundPositionLeft = new Vector2(
(-0.04f * Gdx.graphics.getWidth() / 2f), -28 / 720f
* Gdx.graphics.getHeight() / 2f * (6 / 7f));
groundPositionRight = new Vector2(0.04f * Gdx.graphics.getWidth() / 2f,
-28 / 720f * Gdx.graphics.getHeight() / 2f * (6 / 7f));
level1.createIceHor(0, groundPositionLeft.y + 11.25f);
sprite = new Sprite(new Texture("img/Metal.jpg"));
sprite.setSize(4.5f, 2f);
sprite.setOrigin(sprite.getWidth() / 2f, sprite.getHeight() / 2f);
}
#Override
public void dispose() {
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);
level1.worldStep();
batch.setProjectionMatrix(level1.getCamera().combined);
batch.begin();
batch.end();
renderer.render(level1.getLevel(), level1.getCamera().combined);
level1.getLevel().setContactListener(conlis);
Gdx.input.setInputProcessor(input);
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
private void contactlistener() {
conlis = new ContactListener() {
#Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse) {
// System.out.println(impulse.getNormalImpulses()[0]);
if (impulse.getNormalImpulses()[0] >= 22.648895f) {
if (contact.getFixtureA().getFriction() == 0.1f) {
level1.getLevel().destroyBody(
contact.getFixtureA().getBody());
} else {
level1.getLevel().destroyBody(
contact.getFixtureB().getBody());
}
}
}
#Override
public void endContact(Contact contact) {
}
#Override
public void beginContact(Contact contact) {
}
};
}
}
Have a look at this. It's written for C++ but the general concept still applies.
You aren't allowed to destroy anything while Box2D is doing the simulation step. Your ContactListener is called while this simulation is happening and you instantly destroy the body. That's not allowed. You have to store the bodies to be destroyed and do that right after world.step.
Here you can see how it is done as a quick solution in the tests, but it might not be the best solution.
Related
the Menu Class
package com.gdx.game.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.gdx.game.HuntersGame;
public class InfoScreen implements Screen {
HuntersGame game;
Texture background,backBefore,backAfter,textInfo;
/**
* Constructor, Links the Game instance
* #param game the Game instance provided by the GameScreen, contains the sprite batch
* which is essential for rendering
*/
public InfoScreen(HuntersGame game){
this.game = game;
//play button as image
backBefore = new Texture("backBefore.png");
backAfter = new Texture("backAfter.png");
//text
textInfo = new Texture("info.png");
//background
background = new Texture("grass-info.jpg");
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//positions of back button
int xb= backBefore.getWidth();
int yb= backBefore.getHeight();
//positions of the mouse
int x=Gdx.input.getX(),y=Gdx.input.getY();
//start batch
game.batch.begin();
game.batch.draw(background,0,0,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
game.batch.draw(textInfo,0,-30,Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
//start script for touch and click by mouse
if(x>=0 && x<=backBefore.getWidth() && y>=0 && y<=backBefore.getHeight()){
game.batch.draw(backAfter,0,Gdx.graphics.getHeight()-backBefore.getHeight());
if(Gdx.input.isTouched()){
this.dispose();
game.setScreen(new MenuScreen(game));
}
}else{
game.batch.draw(backBefore,0,Gdx.graphics.getHeight()-backBefore.getHeight());
}
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() {
}
}
I wanted to do a test for this class I don't know how and I tried to import Mockito as every other code did but not work with me I tried for like 6 hours with no result cause I don't know how that Mockito works and search too much with no benefits and I want just an example for that class then I will try to do advanced examples
thank you in advance
PS: for the images i used you can use any image to check the code and for HunterGame class is down
package com.gdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.gdx.game.screens.GameScreen;
import com.gdx.game.screens.MenuScreen;
public class HuntersGame extends Game {
public SpriteBatch batch;
#Override
public void create () {
batch = new SpriteBatch();
this.setScreen(new MenuScreen((this)));
}
#Override
public void dispose () {
batch.dispose();
}
}
[the info class looks like][1]
Hi I'm trying to add tiled map but all time I'm getting the same error:
"Exception in thread "LWJGL Application" com.badlogic.gdx.utils.SerializationException: Error parsing file: mar.tmx
at com.badlogic.gdx.utils.XmlReader.parse(XmlReader.java:83)
at com.badlogic.gdx.maps.tiled.TmxMapLoader.load(TmxMapLoader.java:70)
at com.badlogic.gdx.maps.tiled.TmxMapLoader.load(TmxMapLoader.java:59)"
I saw a similar post and there someone said that my map has the wrong format but I tried every format and still the same. After debugging I got map = null. Anyone have any idea why it doesn't work?
LLL-----------------------
LLL------------------------
LLL-------------------------
LLL--------------------------
LLLL---------------------------
LLL-------------------------
LLL-----------------------
package Screens;
import Scenes.Hud;
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.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.mygdx.game.Marioxx;
public class PlayScreen implements Screen
{
private com.mygdx.game.Marioxx game;
private OrthographicCamera gamecam;
private Viewport gamePort;
//Tiled map variables
private TmxMapLoader maploader;
public TiledMap map;
private OrthogonalTiledMapRenderer renderer;
private Hud hud;
public PlayScreen(com.mygdx.game.Marioxx game)
{
this.game = game;
gamecam = new OrthographicCamera();
gamePort = new FitViewport(Marioxx.V_WIDTH, Marioxx.V_HEIGHT, gamecam);
hud = new Hud(game.batch);
maploader = new TmxMapLoader();
map = maploader.load("mar.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
gamecam.position.set(gamePort.getScreenWidth()/2, gamePort.getScreenHeight()/2, 0);
}
#Override
public void show()
{
}
#Override
public void render(float delta)
{
Gdx.gl.glClearColor(1,0,0,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.setProjectionMatrix(hud.stage.getCamera().combined);
hud.stage.draw();
renderer.render();
}
public void handleInput(float dt )
{
if(Gdx.input.isTouched())
{
gamecam.position.x += 100* dt;
}
}
public void update(float dt)
{
handleInput(dt);
gamecam.update();
renderer.setView(gamecam);
}
#Override
public void resize(int width, int height)
{
gamePort.update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
}
}
I am trying to make my player fall/go down, but he is not. He is just stuck on the map. He can't move. Can you please help?
Here is the code for the Screen. This is where I have all the methods like show, render, resize, pause, resume, hide, etc
package net.hasanbilal.prisonrevelations.screens;
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.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import net.hasanbilal.prisonrevelations.entities.Player;
public class Play implements Screen {
private TiledMap map;
private OrthogonalTiledMapRenderer otmr;
private OrthographicCamera camera;
private Player porter;
#Override
public void show() {
map = new TmxMapLoader().load("maps/level1.tmx");
otmr = new OrthogonalTiledMapRenderer(map);
camera = new OrthographicCamera();
porter = new Player(new Sprite(new Texture("img/porter.png")));
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
otmr.setView(camera);
otmr.render();
otmr.getBatch().begin();
porter.draw(otmr.getBatch());
otmr.getBatch().end();
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.update();
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
dispose();
}
#Override
public void dispose() {
map.dispose();
otmr.dispose();
}
}
Here is the code for the player
package net.hasanbilal.prisonrevelations.entities;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
public class Player extends Sprite {
/**
* x and y velocity
*/
private Vector2 velocity = new Vector2();
//change 120 to 60*2 if it doesn't work
private float speed = 60 * 2, gravity = 60 * 1.8f;
public Player(Sprite s) {
super(s);
}
public void draw(SpriteBatch sb) {
update(Gdx.graphics.getDeltaTime());
super.draw(sb);
}
private void update(float deltaTime) {
velocity.y -= gravity * deltaTime; //gravity to player
if(velocity.y>speed)
velocity.y = speed;
else if(velocity.y < speed)
velocity.y = -speed;
setX(getX() + velocity.x * deltaTime);
setY(getY() + velocity.y * deltaTime);
}
}
This assignment is due soon! Please help!
Nevermind guys, I fixed it. All I had to do is add porter.update(1);between porter.draw(otmr.getBatch()); and otmr.getBatch().end();
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);
}
}
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);
...
}