I'm beginner with libgdx and i looking for answer how to link actor and body(box2d) for a lot time, so please help me :(
I have following code:
/// CLASS ACTOR
public class MyActor extends Actor
{
Texture texture;
float actorX = 0, actorY = 0;
public boolean clicked = false;
public String id;
public MyActor(float x, float y, String id, String tekstura)
{
this.texture = new Texture(Gdx.files.internal(tekstura));
this.id = id;
actorX = x;
actorY = y;
setBounds(actorX, actorY, texture.getWidth(), texture.getHeight());
addListener(new InputListener()
{
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button)
{
MyActor co = ((MyActor) event.getTarget());
co.clicked = true;
System.out.println(co.id);
co.remove();
return true;
}
});
}
#Override
public void draw(SpriteBatch batch, float alpha)
{
batch.draw(texture, actorX, actorY);
}
}
/*....................
.......................
........................
..........................*/
//CREATING SIMPLE OBJECT
MyActor samolot1 = new MyActor(100, 300, "samolot1", "data/jet.png");
samolot1.setTouchable(Touchable.enabled);
stage.addActor(samolot1);
// //////////////// WORLD /////////////////////////////////////////////
// 1
BodyDef bodydef_mojapostac = new BodyDef();
bodydef_mojapostac.type = BodyType.DynamicBody;
bodydef_mojapostac.position.set(400, 100);
CircleShape shape_mojapostac = new CircleShape();
shape_mojapostac.setRadius(30);
FixtureDef fixturedef_mojapostac = new FixtureDef();
fixturedef_mojapostac.density = 0.1f;
fixturedef_mojapostac.friction = 0.8f;
fixturedef_mojapostac.restitution = 0.7f;
fixturedef_mojapostac.shape = shape_mojapostac;
Body BodyMojaPostac = world.createBody(bodydef_mojapostac);
BodyMojaPostac.createFixture(fixturedef_mojapostac);
BodyMojaPostac.setUserData(samolot1);
and render()
......
batch.begin();
world.getBodies(tmpBodies);
for (Body body : tmpBodies)
if (body.getUserData() != null)
{
System.out.println(body.getUserData());
MyActor dupa = (MyActor) body.getUserData();
batch.draw(dupa.texture, dupa.actorX, dupa.actorY);
}
batch.end();
.....
I can link body with sprite but i don't know how with actor :(
After having trouble with this combination as well I'd like to share my solution:
public class PhysicsActor extends Image {
private Body body;
private Fixture fixture;
public PhysicsActor(World world, BodyDef bodyDef, FixtureDef fixtureDef, TextureRegion textureRegion) {
super(textureRegion);
body = world.createBody(bodyDef);
setFixture(getBody().createFixture(fixtureDef));
}
#Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
}
public Body getBody() {
return body;
}
public Fixture getFixture() {
return fixture;
}
I use it like this:
bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(Toolkit.Screen2World(x), Toolkit.Screen2World(y));
pShape = new PolygonShape();
pShape.setAsBox(Toolkit.Screen2World(width/2), Toolkit.Screen2World(height/2)); //In Toolkit I have my methods to scale the world
fixtureDef = new FixtureDef();
fixtureDef.shape = pShape;
//Set some more attributes i.e. density
//Add the PhysicsActor
PhysicsActor leftBar = new PhysicsActor(world, bodyDef, fixtureDef, new TextureRegion(Resources.barLeftTexture, 0, 0, width, height));
leftUpperBar.setSize(width, height);
this.addActor(leftUpperBar);
You only must set your width and height manually (in my case I use the resolution of my Texture).
Resources.barLeftTexture:
public static Texture barLeftTexture;
barLeftTexture = new Texture(Gdx.files.internal("data/barLeft.png"));
I noticed that your question may be outdated for you (the OP) but maybe it helps somebody stumbling across this question.
Related
For some reason, my Box2d Object code works in one Class but does not work in the other even though it is the exact same code I have read it has something to do with importing the correct library but the library is imported correctly but still, it is not working. I'm kind of desperate and don't know what to do, to be honest, maybe someone here can give me a pointer. I know this is a lot of code, but I really don't know what to do, I hope someone can give me a pointer, maybe I am just overlooking something
Here is the code with the Object:
public class Tank extends Sprite implements Renderable, PhysicsObject, Updatable {
public Body body;
public Sprite SpriteBody;
public Sprite SpriteTurret;
public Playscreen playScreen;
public InputProvider input;
public Vector2 aim;
public int readytoshoot=0;
public float canonrotation;
public World world;
public Body b2Body;
TextureRegion TankBlues;
SpriteBatch sb;
public Texture texture;
public Texture arm;
Sprite sprite;
Sprite sparm;
int horizontalForce;
float dt;
float Richtung;
float Speed = 2f;
public float Radius;
private TankType type;
public ArrayList<Flower> flowers;
float PosX,PosY;
Body TankBody,CanonBody;
RevoluteJoint joint;
private Map<ControlSpecification, Integer> controlMap;
private boolean useController;
private int currentLife;
private int maxLife;
private int fullLifeWidth;
// Playscreen playscreen, Vector2 aim, Input Inputprovider,
public Tank(World world, Playscreen screen, SurvivalMode2 survivalMode, TankType tankType) {
flowers = new ArrayList<Flower>();
// super(screen.getAtlas().findRegion("tankBody_blue"));
this.world = world;
canonrotation=0;
// TankBlues = new TextureRegion(getTexture(),0,0 , 46,46);
// setBounds(0, 0, 46 / SEPGame.PPM, 46 / SEPGame.PPM);
// setRegion(TankBlues);
sb = new SpriteBatch();
texture = new Texture(Gdx.files.internal("tankBody_.png"));
arm = new Texture(Gdx.files.internal("b-tankBlue_barrel2_outline.png"));
sprite = new Sprite(texture);
sparm = new Sprite(arm);
PosX=Gdx.graphics.getWidth() / 2 ;
PosY= Gdx.graphics.getHeight() / 2;
sprite.setPosition(PosX,PosY);
sparm.setPosition(Gdx.graphics.getWidth() / 2 - sprite.getWidth() / 2, Gdx.graphics.getHeight() / 2);
useController = false;
// defineTank();
// registerController();
controlMap = StandardControlSpecification.getMapping(tankType);
this.type = tankType;
// defineTank();
// registerController();
// TankBody erstellen
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(PosX, PosY);
PolygonShape shape = new PolygonShape();
shape.setAsBox(sprite.getWidth()/2-1, sprite.getHeight()/2-1);
Radius=(float)Math.sqrt((double)(sprite.getWidth()*sprite.getWidth()/4+sprite.getHeight()*sprite.getHeight()/4) );
FixtureDef fixDef = new FixtureDef();
fixDef.shape = shape;
fixDef.density = 1f;
fixDef.restitution = .1f;
fixDef.friction = .5f;
TankBody = world.createBody(bodyDef);
TankBody.createFixture(fixDef);
TankBody.setLinearDamping(2f);
TankBody.setAngularDamping(2f);
TankBody.setUserData(42);
this.type = tankType;
maxLife = 100;
currentLife = maxLife;
fullLifeWidth = 300;
}
public Rectangle getRect() {
Rectangle Rectanlge = new Rectangle(sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());
return Rectanlge;
}
private void registerController() {
for (Controller controller : Controllers.getControllers()) {
controller.addListener(new GamepadInputProvider(this));
}
}
public float getX() {
return sprite.getX();
}
public float getY() {
return sprite.getY();
}
public float getRotation() {
return sparm.getRotation();
}
public void collision() {
}
public void takeDamage(int damage) {
currentLife -= damage;
}
public void defineTank() { //verwenden wir net physic engine
BodyDef bDef = new BodyDef();
bDef.position.set(sprite.getX(), sprite.getY());
bDef.type = BodyDef.BodyType.DynamicBody;
b2Body = world.createBody(bDef);
FixtureDef fDef = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox(70, 70);
// fDef.density = 1f;
fDef.shape = shape;
b2Body.createFixture(fDef);
}
public void render()
{
sb.begin();
float x=TankBody.getPosition().x-sprite.getWidth()/2;
float y=TankBody.getPosition().y-sprite.getHeight()/2;
sprite.setPosition(x, y);
sprite.setRotation((float)(TankBody.getAngle()/Math.PI*180f));
sparm.setPosition(x, y);
sparm.setRotation((float)(TankBody.getAngle()/Math.PI*180f+canonrotation) );
sprite.draw(sb);
sparm.draw(sb);
sb.end();
Flower destroy = null;
boolean del=false;
for (Flower flower : flowers)
{
if(flower.todelete==0)
{
del=true;
destroy=flower;
}
else
{
flower.render();
}
}
if(del)
{
flowers.remove(destroy);
destroy.delete();
del=false;
}
renderLifebar();
}
Here is the class where it works:
public class Playscreen extends WorldMap implements Screen {
public World world;
public SpriteBatch batch;
public float timeToSimulate;
private SEPGame game;
SpriteBatch sb;
public Tank tank;
public Target ziel;
private Tank gegner1;
boolean treffer;
public float width = Gdx.graphics.getWidth();
public float heights = Gdx.graphics.getHeight();
public WorldMap worldMap;
public Box2DDebugRenderer debugRenderer;
public Obstacle leftwall,upperwall,rightwall,lowerwall;
public Obstacle O1,O2,O3,O4;
public TextureAtlas atlas;
public MenuScreen menuScreen;
int anzahlTotePanzer = 0;
public Playscreen(SEPGame game)
{
world= new World(new Vector2(0,0), false);
ziel = new Target(MathUtils.random(Gdx.graphics.getWidth()-48),MathUtils.random(Gdx.graphics.getHeight()-48),world);
tank = new Tank(world,this, null,TankType.PLAYER_2);
gegner1 = new Tank(world, this, null,TankType.KI);
menuScreen = new MenuScreen(game);
atlas = new TextureAtlas("TanksGesamt.atlas");
leftwall=new Obstacle(world,1);
upperwall=new Obstacle(world,2);
rightwall=new Obstacle(world,3);
lowerwall=new Obstacle(world,4);
O1=new Obstacle(world, 200, 523, 30, 100, 90);
Texture t=new Texture(Gdx.files.internal("crateMetal.png"));
O2=new Obstacle(world, 400, 100, t);
O3=new Obstacle(world, 1200, 900, t);
worldMap = new WorldMap();
this.game = game;
debugRenderer = new Box2DDebugRenderer( true, true,
false, true, true, true );
world.setContactListener(new ContactListener()
{
#Override
public void beginContact(Contact contact)
{
}
#Override
public void endContact(Contact contact)
{
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Body BodyA=contact.getFixtureA().getBody();
if(BodyA.equals(ziel.TargetBody))
{
treffer=true;
}
for (Flower flower : tank.flowers)
{
if(flower.FlowerBody.equals(contact.getFixtureB().getBody())
||flower.FlowerBody.equals(contact.getFixtureA().getBody()))
{
flower.todelete-=1;
}
}
}
#Override
public void preSolve(Contact contact, Manifold oldManifold)
{
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
}
});
}
public void show() {
}
public void create() {
}
public void update(float fval) {
world.step(1 / 60f, 6, 2);
mapRenderer.setView(mainCamera);
}
public void openMenu(){
if(Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)){
game.setScreen(new MenuScreen(game));
this.dispose();
}
}
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1 / 60f, 6, 2);
menuScreen.stage.dispose();
worldMap.render();
worldMap.mainCamera.update();
tank.render();
//tank.moveSprite();
tank.ControllerInput();
gegner1.render();
ziel.render();
tank.moveBody();
if(ziel!=null)
{
ziel.render();
}
if (tank.readytoshoot>0)
{
tank.readytoshoot-=1;
}
debugRenderer.render( world, worldMap.mainCamera.combined );
collision();
if (collision()) {
ziel = new Target(MathUtils.random(Gdx.graphics.getWidth()-48),
MathUtils.random(Gdx.graphics.getHeight()-48),world);
anzahlTotePanzer++;
System.out.println(anzahlTotePanzer);
}
if (treffer)
{
treffer=false;
ziel.delete();
ziel = new Target(MathUtils.random(Gdx.graphics.getWidth()-48),MathUtils.random(Gdx.graphics.getHeight()-48),world);
}
O2.render();
}
public boolean collision() {
boolean col = false;
Rectangle rectangle2 = ziel.bounds();
for(Flower f: tank.flowers) {
Rectangle rec1= f.getRec();
if(rec1.overlaps(rectangle2)){
col= true;
}else {
col= false;
}
}
return col;
}
this is the class which calls the same tank class but gives me a java.lang.UnsatisfiedLinkError: com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape()
public class SurvivalMode2 extends WorldMap implements Screen {
public EnemyTank enemyTank;
public SEPGame game;
public WorldMap worldMap;
public Tank tank;
public int anzahlPanzer;
public int spawnPanzer;
public ArrayList<EnemyTank> tankListe;
public Obstacle O1,O2,O3,O4;
public Obstacle leftwall,upperwall,rightwall,lowerwall;
public Box2DDebugRenderer debugRenderer;
boolean treffer;
public SurvivalMode2(SEPGame game) {
enemyTank = new EnemyTank(world, this,null ,TankType.KI);
tank = new Tank(world,null,this,TankType.PLAYER_1);
this.game = game;
world = new World(new Vector2(0,0), false);
worldMap = new WorldMap();
debugRenderer = new Box2DDebugRenderer
( true, true, false, true, true, true );
world.setContactListener(new ContactListener()
{
#Override
public void beginContact(Contact contact)
{
}
#Override
public void endContact(Contact contact)
{
Fixture fixtureA = contact.getFixtureA();
Fixture fixtureB = contact.getFixtureB();
Body BodyA=contact.getFixtureA().getBody();
if(BodyA.equals(enemyTank.enemyBody))
{
treffer=true;
}
for (Flower flower : tank.flowers)
{
if(flower.FlowerBody.equals(contact.getFixtureB().getBody())
||flower.FlowerBody.equals(contact.getFixtureA().getBody()))
{
flower.todelete-=1;
}
}
}
#Override
public void preSolve(Contact contact, Manifold oldManifold)
{
}
#Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
}
});
}
public void update(){
mapRenderer.setView(mainCamera);
}
#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);
worldMap.render();
worldMap.mainCamera.update();
enemyTank.render();
tank.render();
}
the error I am getting:
Caused by: java.lang.UnsatisfiedLinkError: com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape()J
at com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape(Native Method)
at com.badlogic.gdx.physics.box2d.PolygonShape.<init>(PolygonShape.java:29)
at de.paluno.game.gameobjects.EnemyTank.<init>(EnemyTank.java:51)
at de.paluno.game.screens.SurvivalMode2.<init>(SurvivalMode2.java:54)
at de.paluno.game.screens.MenuScreen.survivalMode(MenuScreen.java:63)
at de.paluno.game.screens.MenuScreen$2.changed(MenuScreen.java:97)
at com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.handle(ChangeListener.java:28)
at com.badlogic.gdx.scenes.scene2d.Actor.notify(Actor.java:183)
at com.badlogic.gdx.scenes.scene2d.Actor.fire(Actor.java:148)
at com.badlogic.gdx.scenes.scene2d.ui.Button.setChecked(Button.java:131)
at com.badlogic.gdx.scenes.scene2d.ui.Button$1.clicked(Button.java:94)
at com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:88)
at com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:59)
at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:350)
at com.badlogic.gdx.backends.lwjgl.LwjglInput.processEvents(LwjglInput.java:342)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:217)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:126)
Here is my code from Enemytank its identical to tank except a few lines like moveBody method or:
package de.paluno.game.gameobjects;
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.math.MathUtils;
import com.badlogic.gdx.physics.box2d.*;
import de.paluno.game.SEPGame;
import de.paluno.game.screens.Playscreen;
import de.paluno.game.screens.SurvivalMode2;
import java.util.ArrayList;
public class EnemyTank extends Sprite {
public ArrayList<EnemyTank> enemyList;
public Sprite enemySprite;
public SpriteBatch enemyBatch;
public PolygonShape shape;
public Texture texture;
private int currentLife;
private int maxLife;
private int fullLifeWidth;
public TankType type;
float PosX,PosY;
public Body enemyBody;
public BodyDef bdef;
public FixtureDef fdef;
public float Radius;
public EnemyTank(World world, SurvivalMode2 survivalScreen, Playscreen screen, TankType tankType){
enemyBatch = new SpriteBatch();
texture = new Texture("tankBody_huge.png");
enemySprite = new Sprite(texture);
PosX= MathUtils.random(Gdx.graphics.getWidth()-48);
PosY= MathUtils.random(Gdx.graphics.getHeight()-48);
bdef = new BodyDef();
fdef = new FixtureDef();
// TankBody erstellen
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(PosX, PosY);
PolygonShape shape = new PolygonShape();
shape.setAsBox(enemySprite.getWidth()/2-1, enemySprite.getHeight()/2-1);
Radius=(float)Math.sqrt((double)(enemySprite.getWidth()*
enemySprite.getWidth()/4+enemySprite.getHeight()*enemySprite.getHeight()/4) );
FixtureDef fixDef = new FixtureDef();
fixDef.shape = shape;
fixDef.density = 1f;
fixDef.restitution = .1f;
fixDef.friction = .5f;
enemyBody = world.createBody(bodyDef);
enemyBody.createFixture(fixDef);
enemyBody.setLinearDamping(2f);
enemyBody.setAngularDamping(2f);
enemyBody.setUserData(42);
this.type = tankType;
maxLife = 100;
currentLife = maxLife;
fullLifeWidth = 300;
}
public float getX() {
return enemySprite.getX();
}
public float getY() {
return enemySprite.getY();
}
public void render() {
enemyBatch.begin();
float x=enemyBody.getPosition().x-enemySprite.getWidth()/2;
float y=enemyBody.getPosition().y-enemySprite.getHeight()/2;
enemySprite.setPosition(x, y);
enemySprite.setRotation((float)(enemyBody.getAngle()/Math.PI*180f));
enemySprite.draw(enemyBatch);
enemyBatch.end();
}
public void setupBody() {
}
public Body getBody() {
return null;
}
public void setBodyToNullReference() {
}
public void update(float fval) {
}
}
java.lang.UnsatisfiedLinkError: com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape()J means Java tries to bind Java method marked native long newPolygonShape() to underlying non-java native method and cannot find it.
In other words there is mismatch between com.badlogic.gdx.physics.box2d Java library and corresponding native library.
I think there reason why it works for one class and does not work for other is you call different methods of PolygonShape and one method is found & binded and other is not.
I am simply trying to render a Box2D body on the screen.
Here is my Core class code:
public class Core extends ApplicationAdapter {
private World world;
private Box2DDebugRenderer rend;
EntityParent p;
private OrthographicCamera cam;
#Override
public void create () {
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.setToOrtho(false);
cam.viewportWidth = 640;
cam.viewportHeight = 480;
world = new World(new Vector2(0, -9.81f), true);
rend = new Box2DDebugRenderer();
p = new EntityParent(world, new Vector2(100, 100), BodyType.DynamicBody);
p.initBodyVariables(1, 1, 1);
p.createCircle(50);
}
#Override
public void render () {
cam.update();
world.step(1/60f, 6, 2);
System.out.println(p.getPosition());
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
rend.render(world, cam.combined);
}
}
And this is the code for the EntityParent:
package com.reality.entity;
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.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
public class EntityParent implements Entity{
/*
* Used for initializing the body
*/
protected Vector2 position;
protected World world;
/*
* All definitions for creating the body
*/
protected BodyType type;
protected BodyDef bodyDef;
protected Body body;
protected FixtureDef fixtureDef;
protected Fixture fixture;
protected float density, friction, restitution;
/**
* Puts body by default at (0,0)
* #param world
* #param type
*/
public EntityParent(World world, BodyType type){
this.world = world;
this.type = type;
this.position = new Vector2(0, 0);
}
/**
*
* #param world
* #param position of body
* #param type
*/
public EntityParent(World world, Vector2 position, BodyType type){
this.world = world;
this.position = position;
this.type = type;
}
/**
*
* #param world
* #param x position of body
* #param y position of body
* #param type
*/
public EntityParent(World world, float x, float y, BodyType type){
this.world = world;
this.position = new Vector2(x, y);
this.type = type;
}
public void initBodyVariables(float density, float friction, float restitution){
this.density = density;
this.friction = friction;
this.restitution = restitution;
}
#Override
public void createPolygonBody(float[] vertices) {
bodyDef = new BodyDef();
bodyDef.type = type;
bodyDef.position.set(position);
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.set(vertices);
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = density;
fixtureDef.friction = friction;
fixtureDef.restitution = restitution;
fixture = body.createFixture(fixtureDef);
shape.dispose();
}
#Override
public void createRectangle(Vector2 dimensions) {
bodyDef = new BodyDef();
bodyDef.type = type;
bodyDef.position.set(position);
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(dimensions.x, dimensions.y);
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = density;
fixtureDef.friction = friction;
fixtureDef.restitution = restitution;
fixture = body.createFixture(fixtureDef);
shape.dispose();
}
#Override
public void createCircle(float radius) {
bodyDef = new BodyDef();
bodyDef.type = type;
bodyDef.position.set(position);
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setRadius(radius);
fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = density;
fixtureDef.friction = friction;
fixtureDef.restitution = restitution;
fixture = body.createFixture(fixtureDef);
shape.dispose();
}
#Override
public void update() {
}
#Override
public void render(Box2DDebugRenderer renderer) {
}
#Override
public Vector2 getPosition() {
return this.position;
}
}
So what happens when I run this I get the following error:
AL lib: (EE) alc_cleanup: 1 device not closed
Assertion failed!
Program: C:\Program Files\Java\jre1.8.0_60\bin\javaw.exe
File: /var/lib/jenkins/workspace/libgdx/extensions/gdx-box2d/gdx-box2d/jni/Box2D/Collision/Shapes/b2PolygonShape.cpp, Line 384
Expression: m_count >= 3
If I get rid of the statement from the core class
p.initBodyVariables(1, 1, 1);
I simply get a blank screen.
I tested to see if it was the world and the world said there is one body in it so it is registering, but I just don't get why it is throwing this error and not rendering at all. Any help is greatly appreciated thanks!
You are using wrong type of shape - PolygonShape instead of CircleShape when creating circles:
#Override
public void createCircle(float radius) {
bodyDef = new BodyDef();
bodyDef.type = type;
bodyDef.position.set(position);
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape(); //here it should be CircleShape
shape.setRadius(radius);
It should be:
CircleShape shape = new CircleShape();
So I have tried several different ways to put the sprite on to my coin bodies but to no avail. I initially just tried putting a texture on it, but that didn't work. Then I tried using the texture packer and atlas to see if that would help. Here is my code:
public class Coin extends Item {
public Coin(PlayScreen screen, float x, float y) {
super(screen, x, y);
setRegion(screen.getAtlas().findRegion("Coin"), 0, 0, 15, 16);
}
#Override
public void defineItem() {
BodyDef bdef = new BodyDef();
bdef.position.set(getX(), getY());
bdef.type = BodyDef.BodyType.DynamicBody;
body = world.createBody(bdef);
FixtureDef fdef = new FixtureDef();
CircleShape shape = new CircleShape();
shape.setRadius(10/Racing.PPM);
fdef.shape = shape;
Filter filter = new Filter();
filter.categoryBits = Racing.COIN_BIT;
Fixture fixture = body.createFixture(fdef);
fixture.setFilterData(filter);
fixture.setUserData(this);
}
public void update(float dt){
super.update(dt);
setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 2);
}
}
And it extends this class:
public abstract class Item extends Sprite{
protected PlayScreen screen;
protected World world;
protected Vector2 velocity;
protected boolean toDestroy;
protected boolean destroyed;
protected Body body;
public Item(PlayScreen screen, float x, float y){
this.screen = screen;
this.world = screen.getWorld();
toDestroy = false;
destroyed = false;
setPosition(x, y);
setBounds(getX(), getY(), 16 / Racing.PPM, 16 / Racing.PPM);
defineItem();
}
public abstract void defineItem();
public abstract void collect(Kart kart);
public void update(float dt){
if(toDestroy && !destroyed){
world.destroyBody(body);
destroyed = true;
}
}
public void draw(Batch batch){
if(!destroyed){
super.draw(batch);
}
}
public void destroy(){
toDestroy = true;
}
}
Any help would be greatly appreciated! Thanks!
Like my question says can someone tell me, why does my circle texture/sprite are acting like a rectangle ?
Code:
`
#Override
public void create() {
batch = new SpriteBatch();
img = new Texture("ball.png");
sprite = new Sprite(img);
sprite.setPosition(-sprite.getWidth()/2,-sprite.getHeight()/2);
world = new World(new Vector2(0, -1f),true);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set((sprite.getX() + sprite.getWidth()/2) /
PIXELS_TO_METERS,
(sprite.getY() + sprite.getHeight()/2) / PIXELS_TO_METERS);
body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(sprite.getWidth()/2 / PIXELS_TO_METERS, sprite.getHeight()
/2 / PIXELS_TO_METERS);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 0.1f;
fixtureDef.restitution = 0.8f;
body.createFixture(fixtureDef);
shape.dispose();
//CONTINUE
// BOTTOM
BodyDef bodyDefBottom = new BodyDef();
bodyDefBottom.type = BodyDef.BodyType.StaticBody;
float w = Gdx.graphics.getWidth()/PIXELS_TO_METERS;
// Set the height to just 50 pixels above the bottom of the screen so we can see the edge in the
// debug renderer
float h = Gdx.graphics.getHeight()/PIXELS_TO_METERS- 50/PIXELS_TO_METERS;
bodyDefBottom.position.set(0,0);
FixtureDef fixtureDef2 = new FixtureDef();
EdgeShape edgeShape = new EdgeShape();
edgeShape.set(-w/2,-h/2,w/2,-h/2);
fixtureDef2.shape = edgeShape;
bodyEdgeScreenBottom = world.createBody(bodyDefBottom);
bodyEdgeScreenBottom.createFixture(fixtureDef2);
edgeShape.dispose();
// TOP
BodyDef bodyDefTop = new BodyDef();
bodyDefTop.type = BodyDef.BodyType.StaticBody;
w = Gdx.graphics.getWidth()/PIXELS_TO_METERS;
// Set the height to just 50 pixels above the bottom of the screen so we can see the edge in the
// debug renderer
h = Gdx.graphics.getHeight()/PIXELS_TO_METERS;
bodyDefTop.position.set(0,0);
fixtureDef2 = new FixtureDef();
edgeShape = new EdgeShape();
edgeShape.set(-w/2,h/2,w/2,h/2);
fixtureDef2.shape = edgeShape;
bodyEdgeScreenTop = world.createBody(bodyDefTop);
bodyEdgeScreenTop.createFixture(fixtureDef2);
edgeShape.dispose();
// LEFT
BodyDef bodyDefLeft = new BodyDef();
bodyDefLeft.type = BodyDef.BodyType.StaticBody;
w = Gdx.graphics.getWidth()/PIXELS_TO_METERS;
// Set the height to just 50 pixels above the bottom of the screen so we can see the edge in the
// debug renderer
h = Gdx.graphics.getHeight()/PIXELS_TO_METERS;
bodyDefLeft.position.set(0,0);
fixtureDef2 = new FixtureDef();
edgeShape = new EdgeShape();
edgeShape.set(w/2,-h/2,w/2,h/2);
fixtureDef2.shape = edgeShape;
bodyEdgeScreenLeft = world.createBody(bodyDefLeft);
bodyEdgeScreenLeft.createFixture(fixtureDef2);
edgeShape.dispose();
// RIGHT
BodyDef bodyDefRight = new BodyDef();
bodyDefRight.type = BodyDef.BodyType.StaticBody;
w = Gdx.graphics.getWidth()/PIXELS_TO_METERS;
// Set the height to just 50 pixels above the bottom of the screen so we can see the edge in the
// debug renderer
h = Gdx.graphics.getHeight()/PIXELS_TO_METERS;
bodyDefRight.position.set(0,0);
fixtureDef2 = new FixtureDef();
edgeShape = new EdgeShape();
edgeShape.set(-w/2,-h/2,-w/2,h/2);
fixtureDef2.shape = edgeShape;
bodyEdgeScreenRight = world.createBody(bodyDefRight);
bodyEdgeScreenRight.createFixture(fixtureDef2);
edgeShape.dispose();
//CONTINUE
Gdx.input.setInputProcessor(this);
//debugRenderer = new Box2DDebugRenderer();
font = new BitmapFont();
font.setColor(Color.BLACK);
camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.
getHeight());
}
private float elapsed = 0;
#Override
public void render() {
camera.update();
// Step the physics simulation forward at a rate of 60hz
world.step(1f / 60f, 6, 2);
body.applyTorque(torque, true);
sprite.setPosition((body.getPosition().x * PIXELS_TO_METERS) - sprite.
getWidth() / 2,
(body.getPosition().y * PIXELS_TO_METERS) - sprite.getHeight() / 2)
;
sprite.setRotation((float) Math.toDegrees(body.getAngle()));
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
//debugMatrix = batch.getProjectionMatrix().cpy().scale(PIXELS_TO_METERS,
// PIXELS_TO_METERS, 0);
batch.begin();
if(drawSprite)
batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),
sprite.getOriginY(),
sprite.getWidth(),sprite.getHeight(),sprite.getScaleX(),sprite.
getScaleY(),sprite.getRotation());
font.draw(batch,
"Restitution: " + body.getFixtureList().first().getRestitution(),
-Gdx.graphics.getWidth()/2,
Gdx.graphics.getHeight()/2 );
batch.end();
//debugRenderer.render(world, debugMatrix);
}
#Override
public void dispose() {
img.dispose();
world.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
// On touch we apply force from the direction of the users touch.
// This could result in the object "spinning"
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
body.applyForce(1f,1f,screenX,screenY,true);
//body.applyTorque(0.4f,true);
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
`
I have tried searching for other posts but couldn't find anything that explains to me why it is acting like a rectangle and how to resolve this. I have also tried searching for other methods to draw the texture , even using CircleShape but that cannot put inside texture from image. I'm pretty newbie in libgdx, I'm still learning everyday.
I'm little confused... You are creating PolygonShape and expecting it will behave as circle?
PolygonShape shape = new PolygonShape();
shape.setAsBox(...
All you can achieve this way is polygon with ball sprite inside. If you want to have a circle use mentioned by you CircleShape
CircleShape shape = new CircleShape();
shape.setRadius(1); //or anything you need
...
//assing it to the fixture etc
then update it when drawing with its position and angle - that's all
i'm trying to make a program with Box2D and libgdx that makes the character jump on a static body (here, a circle). But my camera (that is following the dynamic body (the player)) keeps going down, even if my character stays on top of the circle as intended. So my questions are :
1) Why my camera keeps falling down, when it's supposed to follow the "playerBody" that is staying on top of the static body ?
2) Why my camera bounce when I press the Z key, but not my playerbody ?
Thanks in advance. You may try to run it in eclipse, to see better what I mean, here's what I put in my Activity class :
(I got no errors/warnings at all.)
//private SpriteBatch batch;
//private Texture texture;
//private Sprite sprite;
//public Body body;
World world;
Body playerBody;
Body planetBody;
CircleShape planetCircle;
PolygonShape playerBox;
OrthographicCamera camera;
Box2DDebugRenderer debugRenderer;
static final float BOX_STEP=1/60f;
static final int BOX_VELOCITY_ITERATIONS=6;
static final int BOX_POSITION_ITERATIONS=2;
static final float WORLD_TO_BOX=0.01f;
static final float BOX_WORLD_TO=100f;
boolean jump = false;
long lastGroundTime = 0;
#Override
public void create() {
world = new World(new Vector2(0, -50), true);
debugRenderer = new Box2DDebugRenderer();
camera = new OrthographicCamera();
camera.viewportHeight = 320;
camera.viewportWidth = 480;
camera.position.set(camera.viewportWidth * .5f, camera.viewportHeight * .5f, 0f);
camera.update();
//Ground body
/*BodyDef groundBodyDef =new BodyDef();
groundBodyDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2 - 100 + 125);
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox((camera.viewportWidth) * 2, 10.0f);
groundBody.createFixture(groundBox, 0.0f);
*/
//Planet
BodyDef planetDef = new BodyDef();
planetDef.type = BodyType.StaticBody;
planetDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2 - 100);
Body planetBody = world.createBody(planetDef);
CircleShape planetCircle = new CircleShape();
planetCircle.setRadius(125f);
FixtureDef planetFixtureDef = new FixtureDef();
planetFixtureDef.shape = planetCircle;
planetFixtureDef.density = 1.0f;
//planetFixtureDef.friction = 0.0f;
//planetFixtureDef.restitution = 0;
planetBody.createFixture(planetFixtureDef);
//Player
BodyDef playerBodyDef = new BodyDef();
playerBodyDef.type = BodyType.DynamicBody;
playerBodyDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2 - 100 + 125 + 50);
playerBody = world.createBody(playerBodyDef);
PolygonShape playerBox = new PolygonShape();
playerBox.setAsBox(5.0f, 15.0f);
FixtureDef playerFixtureDef = new FixtureDef();
playerFixtureDef.shape = playerBox;
playerFixtureDef.density = 1.0f;
//playerFixtureDef.friction = 1.0f;
//playerFixtureDef.restitution = 1;
playerBody.createFixture(playerFixtureDef);
playerBody = world.createBody(playerBodyDef);
//Dynamic Body
/*BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2);
Body body = world.createBody(bodyDef);
CircleShape dynamicCircle = new CircleShape();
dynamicCircle.setRadius(5f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 1;
body.createFixture(fixtureDef); */
Gdx.input.setInputProcessor(this);
}
#Override
public void dispose() {
/*batch.dispose();
texture.dispose();*/
/*dynamicCircle.dispose();
groundBox.dispose();*/
playerBox.dispose();
planetCircle.dispose();
}
#Override
public void render() {
//Gdx.gl.glClearColor(1, 1, 1, 1);
update();
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
/*batch.setProjectionMatrix(camera.combined);
batch.begin();
//sprite.draw(batch);
batch.end();*/
camera.position.set(playerBody.getPosition().x, playerBody.getPosition().y, 0);
camera.update();
//camera.apply(Gdx.gl10);
debugRenderer.render(world, camera.combined);
world.step(BOX_STEP, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);
//playerBody.setAwake(true);
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
public void update()
{
if(jump == true /*Gdx.input.isKeyPressed(Gdx.input.)*/ && grounded() == true)
{
playerBody.setLinearVelocity(0, 0);
playerBody.applyLinearImpulse(new Vector2(0,150), new Vector2(playerBody.getPosition().x, playerBody.getPosition().y));
jump = false;
}
//playerBody.setTransform(new Vector2(camera.viewportWidth / 2, playerBody.getPosition().y), playerBody.getAngle());
//planetBody.setTransform(new Vector2(camera.viewportWidth / 2, camera.viewportHeight / 2), 0);
}
#Override
public void resume() {
}
#Override
public boolean keyDown(int keycode) {
//if(keycode == Keys.S)
return false;
}
#Override
public boolean keyUp(int keycode) {
if(keycode == Keys.Z)
jump = true;
return false;
}
public boolean grounded()
{
if(playerBody.getPosition().y <= ((camera.viewportHeight / 2) - 100 + 125))
{
return true;
}
else
{
return false;
}
}
You are creating two playerBody in the world. The second one is assigned but has no fixture. This is the one you are manipulating in your code and your camera is following. Remove the second playerBody = world.createBody(playerBodyDef); and it should work (better).