Box2D Body not rendering and crashing - java

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

Related

The object coordinates doesn't appear at right place

I had to adjust my scene coordinates to find useful gravity for my objects.
So I decided to reduce the screen coordinates so that the gravity behavior on my objects was getting ok.
But I have a problem right now, is that when I type sprite.setPosition(0,0), the sprite seems doesn't appear in the right place.
Here is my code:
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
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.math.Vector2;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
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.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.World;
public class MyGdxGame extends ApplicationAdapter {
public OrthographicCamera camera;
Sound sound;
BitmapFont font,font2;
SpriteBatch batch;
Texture img1,img2,img3,img4,img5,img6;
Sprite sprite1,sprite2,sprite3;
World world;
Body solKose,sagKose,ustKose,altKose,body1,body2,body3;
int width=0;
float axes=0;
private int enemyGoalCounter, playerGoalCounter=0;
Sphere _player;
Sphere _enemyPlayer;
Sphere ball;
Vector2 directionVector;
Vector3 touchCoordinate;
int direction=-1;
#Override
public void create () {
camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
camera.viewportWidth = Gdx.graphics.getWidth()/100;
camera.viewportHeight = Gdx.graphics.getHeight()/100;
camera.update();
font = new BitmapFont();
font2 = new BitmapFont();
font.setColor(Color.RED);
font2.setColor(Color.BLUE);
touchCoordinate = new Vector3(0,0,0);
sound = Gdx.audio.newSound(Gdx.files.internal("taktak.wav"));
batch = new SpriteBatch();
img1 = new Texture("sphere2.png");
img2 = new Texture("sphere2.png");
img3 = new Texture("ball.png");
sprite1 = new Sprite(img1);
sprite2 = new Sprite(img2);
sprite3 = new Sprite(img3);
sprite1.setPosition(0,0);
sprite2.setPosition(0,0);
world = new World(new Vector2(0, 0),true);
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(sprite1.getX()/2,sprite1.getY()/2);
body1 = world.createBody(bodyDef);
CircleShape shape = new CircleShape();
shape.setRadius(1f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.restitution=0.6f;
body1.createFixture(fixtureDef);
shape.dispose();
BodyDef bodyDef2 = new BodyDef();
bodyDef2.type = BodyDef.BodyType.DynamicBody;
bodyDef2.position.set(sprite2.getX()/2,sprite2.getY()/2);
body2 = world.createBody(bodyDef2);
CircleShape shape2 = new CircleShape();
shape2.setRadius(1f);
FixtureDef fixtureDef2 = new FixtureDef();
fixtureDef2.shape = shape2;
fixtureDef.restitution=0.6f;
body2.createFixture(fixtureDef2);
shape2.dispose();
}
#Override
public void render () {
System.out.println();
camera.update();
play();
inputController(); // A function for keyboard input controlling
math(); // For Collision controlling
world.step(1f/60f, 6, 2);
sprite1.setPosition(body1.getPosition().x,body1.getPosition().y);
sprite2.setPosition(body2.getPosition().x,body2.getPosition().y);
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(sprite1,sprite1.getX(),sprite1.getY(),2,2);
batch.draw(sprite2,sprite2.getX(),sprite2.getY(),2,2);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
world.dispose();
}
void play() {
}
void inputController() {
if(Gdx.input.isTouched()){
Vector2 directionVector = new Vector2(0,0);
touchCoordinate.x = Gdx.input.getX();
touchCoordinate.y = Gdx.input.getY();
camera.unproject(touchCoordinate);
double distance = Math.pow(sprite1.getWidth()/2,2)-(Math.pow((sprite1.getOriginX()-touchCoordinate.x),2)+Math.pow((sprite1.getOriginY()-touchCoordinate.y),2));
System.out.println(touchCoordinate);
if(distance>0){
body1.applyForceToCenter(20,20,true);
}else if(distance==0){
body1.applyForceToCenter(20,20,true);
}else{
////
}
}
//_player.setCenterPosition(touchCoordinate.x,touchCoordinate.y);
}
void math() {
goalSystem();
}
void restartPositions(){
}
void goalSystem() {
/*
if(!goal) {
if(ball.getCenterPosition(ball.position.x, ball.position.y).y < 20) {
if((ball.getCenterPosition(ball.position.x, ball.position.y).x >= Gdx.graphics.getWidth()/2-325/2) && (ball.getCenterPosition(ball.position.x, ball.position.y).x <= Gdx.graphics.getWidth()/2+325/2)) {
goal=true;
enemyGoalCounter++;
restartPositions();
}
}
if(ball.getCenterPosition(ball.position.x, ball.position.y).y > Gdx.graphics.getHeight()-20) {
if((ball.getCenterPosition(ball.position.x, ball.position.y).x >= Gdx.graphics.getWidth()/2-325/2) && (ball.getCenterPosition(ball.position.x, ball.position.y).x <= Gdx.graphics.getWidth()/2+325/2)) {
goal=true;
playerGoalCounter++;
restartPositions();
}
}
}
*/
}
public class Sphere{
Vector2 firstPos,firstDirection;
float firstSpeed;
Vector2 position, direction,centerPosition;
float x,y,width,height;
float radius;
float xCenter,yCenter;
float speed;
float velocity;
public Sphere(float x, float y, float radius, float width, float height) {
this.x = x;
this.y = y;
this.radius = radius;
this.width = width;
this.height = height;
this.position = new Vector2(x,y);
this.direction = new Vector2(x,y);
this.speed = 0;
this.firstSpeed = speed;
this.firstPos = new Vector2(x,y);
this.firstDirection = new Vector2(x,y);
}
Vector2 getCenterPosition(float x, float y) {
centerPosition = new Vector2(x+width/2,y);
return centerPosition;
}
void setCenterPosition(float x, float y){
position.x = x-width/2;
position.y = y-height/2;
}
void setSpeed(float speed) {
this.speed = speed;
}
float getSpeed() {
return this.speed;
}
}
}
Image:
I think the issue is the camera and viewport not a rendered position issue. Your code to set the camera and viewport can be changed. If you are using viewports -You- decide the coordinate range for rendering, its arbitary. This rendering is -then- scaled as you like to fit the screen. In your case you get the width and height of the device (which is not constant across devices even aspect ratio changes) before setting your own viewport parameters?
So try instead
camera = new OrthographicCamera(100, 500); //You pick as you like
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0); //centre camera
viewport = new FitViewport(camera.viewportWidth, camera.viewportHeight, camera);//stretch proportionally
Read this as well
How Camera works in Libgdx and together with Viewport
(Also you didn't add the offset to y here.
Vector2 getCenterPosition(float x, float y) {
centerPosition = new Vector2(x+width/2,y);
....
)

How to create movingPlatform?

I want to create platform that moving right/left with box2d, but I don't know how?
I create platform-body and gave him KinematicType, and trying to move it with setLinearVelocity, but it doesn't help
This is how I create platform "bucket":
package com.niceboy.game.Objects;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.physics.box2d.Body;
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.physics.box2d.World;
import java.util.Random;
import static com.niceboy.game.Constants.PLATFORM_MARGIN;
import static com.niceboy.game.Constants.PPM;
public class Bucket {
private Random rand = new Random();
private World world;
private Body body;
public Bucket(World world){
this.world = world;
}
public void createBucket(int y){
BodyDef bdef = new BodyDef();
bdef.position.set(rand.nextInt(Gdx.graphics.getWidth())/PPM,PLATFORM_MARGIN/PPM*y);
bdef.type = BodyDef.BodyType.KinematicBody;
body = world.createBody(bdef);
PolygonShape box = new PolygonShape();
box.setAsBox(50/PPM,20/PPM);
FixtureDef fdef = new FixtureDef();
fdef.shape = box;
body.createFixture(fdef).setUserData("bucket");
}
public void repos(int y){
body.getPosition().set(rand.nextInt(Gdx.graphics.getWidth())/PPM,PLATFORM_MARGIN/PPM*y);
}
}
But Idon't know how to move it
kinematicBody->setLinearVelocity(1,0); //move right 1 unit per second
I've created KinematicBody body and give him PolygonShape and apply linear velocity than body start moving, when you want to change direction apply same velocity in negative magnitude so that it start moving in opposite direction.
public class MainGame extends InputAdapter implements ApplicationListener {
private SpriteBatch batch;
private ExtendViewport extendViewport;
private OrthographicCamera cam;
private float w=20;
private float h=22;
private World world;
private Box2DDebugRenderer debugRenderer;
private Array<Body> array;
private Vector3 vector3;
private Body platform;
Vector2 vector2;
boolean isLeft;
#Override
public void create() {
vector2=new Vector2();
isLeft=true;
cam=new OrthographicCamera();
extendViewport=new ExtendViewport(w,h,cam);
batch =new SpriteBatch();
Gdx.input.setInputProcessor(this);
world=new World(new Vector2(0,-9.8f),true);
array=new Array<Body>();
debugRenderer=new Box2DDebugRenderer();
vector3=new Vector3();
BodyDef bodyDef=new BodyDef();
bodyDef.type= BodyDef.BodyType.KinematicBody;
bodyDef.position.set(0,0);
platform=world.createBody(bodyDef);
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(3,1);
FixtureDef fixtureDef=new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.restitution=.5f;
platform.createFixture(fixtureDef);
polygonShape.dispose();
platfrom.setLinearVelocity(1,0);
}
#Override
public void render() {
Gdx.gl.glClearColor(0,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(1/60f,6,2);
batch.setProjectionMatrix(cam.combined);
batch.begin();
world.getBodies(array);
for (Body body:array){
if(body.getUserData()!=null) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setPosition(body.getPosition().x-sprite.getWidth()/2, body.getPosition().y-sprite.getHeight()/2);
sprite.setRotation(body.getAngle()*MathUtils.radDeg);
sprite.draw(batch);
}
}
batch.end();
debugRenderer.render(world,cam.combined);
Vector2 pos=platfrom.getTransform().getPosition();
if(pos.x>20-3) {
platfrom.setLinearVelocity(-1,0);
}
if(pos.x<3) {
platfrom.setLinearVelocity(1,0);
}
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void resize(int width, int height) {
extendViewport.update(width,height);
cam.position.x = w /2;
cam.position.y = h/2;
cam.update();
}
private void createPhysicsObject(float x,float y){
float sizeX=0.5f,sizeY=0.5f;
BodyDef bodyDef=new BodyDef();
bodyDef.position.set(x,y);
bodyDef.type= BodyDef.BodyType.DynamicBody;
Body body=world.createBody(bodyDef);
PolygonShape polygonShape=new PolygonShape();
polygonShape.setAsBox(sizeX,sizeY);
FixtureDef fixtureDef=new FixtureDef();
fixtureDef.shape=polygonShape;
fixtureDef.restitution=.2f;
fixtureDef.density=2;
body.createFixture(fixtureDef);
body.setFixedRotation(false);
polygonShape.dispose();
Sprite sprite=new Sprite(new Texture("badlogic.jpg"));
sprite.setSize(2*sizeX,2*sizeY);
sprite.setPosition(x-sprite.getWidth()/2,y-sprite.getHeight()/2);
sprite.setOrigin(sizeX,sizeY);
body.setUserData(sprite);
}
#Override
public void dispose() {
batch.dispose();
debugRenderer.dispose();
world.dispose();
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
vector3.set(screenX,screenY,0);
Vector3 position=cam.unproject(vector3);
createPhysicsObject(vector3.x,vector3.y);
return false;
}
}

Libgdx body position and shaperenderer position not the same

i'm fairly new to libgdx in general. Basically I have the ball bouncing world and i am just experimenting with it. Before I had a fixed camera position as such:
http://prntscr.com/567hvo
After I have putted the following line in the render method so the camera keeps following the player (which is the circle) :
camera.position.set(player.getPosition().x, player.getPosition().y, 0);
The player is a Body type.
So when I do this it does follow the player, but the shape renderer acts weird now. Look at what happens:
http://prntscr.com/567i9a
Even though I am referring to the same x and y position of the player to the camera and the shape renderer, they are not in the same position.
Here is my code:
public class Game extends ApplicationAdapter {
World world = new World(new Vector2(0, -9.8f), true);
Box2DDebugRenderer debugRenderer;
OrthographicCamera camera;
static final int PPM = 100;
static float height,width;
Body player;
RayHandler handler;
PointLight l1;
ShapeRenderer shapeRenderer;
#Override
public void create() {
shapeRenderer = new ShapeRenderer();
height = Gdx.graphics.getHeight();
width = Gdx.graphics.getWidth();
//set camera
camera = new OrthographicCamera();
camera.setToOrtho(false, (width)/PPM/2, (height)/PPM/2);
camera.update();
//Ground body
BodyDef groundBodyDef =new BodyDef();
groundBodyDef.position.set(new Vector2(width/PPM/2/2, 0));
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox((width/PPM/2/2), 0.1f);
groundBody.createFixture(groundBox, 0.0f);
//wall left
BodyDef wallLeftDef = new BodyDef();
wallLeftDef.position.set(0, 0f);
Body wallLeftBody = world.createBody(wallLeftDef);
PolygonShape wallLeft = new PolygonShape();
wallLeft.setAsBox(width/PPM/20/2, height/PPM/2);
wallLeftBody.createFixture(wallLeft,0.0f);
//wall right
BodyDef wallRightDef = new BodyDef();
wallRightDef.position.set((width/PPM)/2, 0f);
Body wallRightBody = world.createBody(wallRightDef);
PolygonShape wallRight = new PolygonShape();
wallRight.setAsBox(width/PPM/20/2, height/PPM/2);
wallRightBody.createFixture(wallRight,0.0f);
//Dynamic Body
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set((width/PPM)/2/2, (height / PPM)/2/2);
player = world.createBody(bodyDef);
CircleShape dynamicCircle = new CircleShape();
dynamicCircle.setRadius(5f/PPM);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 0.4f;
fixtureDef.friction = 0.2f;
fixtureDef.restitution = 0.6f;
player.createFixture(fixtureDef);
debugRenderer = new Box2DDebugRenderer();
//Lighting
handler = new RayHandler(world);
handler.setCombinedMatrix(camera.combined);
PointLight l1 = new PointLight(handler,5000,Color.CYAN,width/PPM/2,width/PPM/2/2/2,height/PPM/2/2);
new PointLight(handler,5000,Color.PURPLE,width/PPM/2,width/PPM/2/1.5f,height/PPM/2/2);
shapeRenderer.setProjectionMatrix(camera.combined);
}
public void update() {
if(Gdx.input.isKeyJustPressed(Keys.UP)) {
player.applyForceToCenter(0, 0.75f, true);
}
if(Gdx.input.isKeyJustPressed(Keys.RIGHT)) {
player.applyForceToCenter(0.5f, 0f, true);
}
if(Gdx.input.isKeyJustPressed(Keys.LEFT)) {
player.applyForceToCenter(-0.5f, 0f, true);
}
}
#Override
public void dispose() {
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
debugRenderer.render(world, camera.combined);
world.step(1/60f, 6, 2);
handler.updateAndRender();
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(1, 1, 1, 1);
shapeRenderer.circle(player.getPosition().x, player.getPosition().y, 5f/PPM, 100);
shapeRenderer.end();
camera.position.set(player.getPosition().x, player.getPosition().y, 0);
camera.update();
update();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
You are only setting the shapeRenderers projectionmatrix once so it is not updating when you render.
You should put
shapeRenderer.setProjectionMatrix(camera.combined);
to your render method right before
shapeRenderer.begin(ShapeType.Filled);

box2d : camera and body not synced

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

Libgdx: Actor as body

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.

Categories

Resources