Libgdx box2d body stuck
I am creating a game with libgdx and box2d and right now have created a rectangle body. The body is a "block" which can be flung by the player to try and block a ball.
The problem I am having is that the body is stuck at the position (0, 47.5184) even though that is not the position where it was set. I can even set the postion to something crazy like (-10000, -10000) and it will still render at (0, 47.5184).
The rectangle still works fine with the fling but it simply starts at the wrong spot and cannot be changed.
In my code, I create the body by calling the createBlock and setBlockProperties methods. These Methods are called in the "show" function Also note that the ball used for the game was created the exact same way and works fine.
Code:
public class GameScreen extends ScreenAdapter {
Controller game;
public World world;
public Body ball;
public Body block;
public Box2DDebugRenderer box2DDebugRenderer;
private Matrix4 cameraBox2D;
public MyGestureListener myGestureListener;
//x-axis length for top/bottom bar
private float goalWidth;
//pixels per meter
public float PPM;
//y-axis height for back bar
private float goalHeight;
private float goalPostThickness;
//Screen height and width
private float screenWidth;
private float screenHeight;
//How far down/up posts are from edge of screen
private float goalPostTopOffset;
private float goalPostBottomOffset;
//Center x,y of cannon
private float cannonOriginX; //Variables used for starting poisition of balls
private float cannonOriginY;
//Center x,y of ball
float ballX;
float ballY;
//Velocity of ball
public float velocity = 50;
//Tracks users drag y coord
public float panLocation = 0;
//Velocity of block once the user releases
public float flingVelocity;
//Changes to true when the block is released
public boolean isReleased = false;
public GameScreen (Controller game){
this.game = game;
}
@Override
public void show(){
myGestureListener = new MyGestureListener(game, this);
cameraBox2D = new Matrix4(game.cam.combined);
screenWidth = game.getScreenWidth();
screenHeight = game.getScreenHeight();
PPM = screenHeight / 80;
goalPostTopOffset = screenHeight/7;
goalPostBottomOffset = goalPostTopOffset * 3;
goalHeight = screenHeight - (goalPostTopOffset + goalPostBottomOffset);
goalWidth = screenWidth / 6;
goalPostThickness = screenWidth / 75;
cannonOriginX = goalWidth / 2; //Variables used for starting position of balls
cannonOriginY = (goalPostThickness*5) / 2;
ballX = 0 + cannonOriginX;
ballY = (goalPostBottomOffset - (goalPostBottomOffset / 4)) + cannonOriginY;
world = new World(new Vector2(0, 0f), true);
box2DDebugRenderer = new Box2DDebugRenderer();
//Creates animated ball
ball = createBall();
//Sets radius, density, etc.
setBallProperties(ball);
//Creates block that stops balls
block = createBlock();
//Sets properties
setBlockProperties(block);
}
@Override
public void render(float delta){
//Logic
world.step(1/60f, 6, 2);
//Draw
game.cam.update();
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
box2DDebugRenderer.render(world, game.cam.combined.scl(PPM));
game.shape.setProjectionMatrix(game.cam.combined);
Gdx.input.setInputProcessor(new GestureDetector(myGestureListener));
System.out.println(block.getPosition().y);
System.out.println(block.getPosition().x);
drawNonAnimated();
drawAnimated();
//show()
cameraBox2D = game.cam.combined.cpy(); //Copy the main camera
cameraBox2D.scl(PPM); //Scale the camera projection to the ratio you're using for Box2D
//render()
box2DDebugRenderer.render(world, cameraBox2D);
}
@Override
public void hide(){
}
//draws stationary objects such as goal posts
public void drawNonAnimated(){
//Cannon platform
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, goalWidth/PPM, (goalPostThickness*2)/PPM);
game.shape.end();
//Cannon
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, cannonOriginX/PPM,
cannonOriginY/PPM, goalWidth/PPM, (goalPostThickness*5)/PPM, 1, 1, 45);
game.shape.end();
}
public void drawAnimated(){
//FOR BALL
velocity--;
ball.setLinearVelocity(new Vector2(35,velocity));
Vector2 pos = ball.getPosition();
if (pos.x >= screenWidth/PPM){
ball.setTransform(new Vector2(ballX/PPM, ballY/PPM), 0);
//max 75 min 50
velocity = randInt(50, 75);
}
//Attaching a regular libgdx shape to the position of box2d shape
game.circle.setColor(1, 1, 1, 1);
game.circle.begin(ShapeRenderer.ShapeType.Filled);
game.circle.circle(pos.x*PPM, pos.y*PPM, goalPostThickness * 1.5f);
game.circle.end();
game.cam.update();
blockerMovement();
}
public void blockerMovement(){
//FOR BLOCKER RECTANGLE ANIMATION
Vector2 pos = block.getPosition();
float boundaryLocation = (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM;
//attachBlockerShape(pos);
panLocation = myGestureListener.getPanLocation();
if (isReleased == true){
//Get the velocity as the block is released
//to determine the speed it will continue to go after release
block.setLinearVelocity(0, flingVelocity);
flingVelocity -= 3;
}
else if (myGestureListener.getCheckRelease()|| panLocation/PPM >= boundaryLocation && !isReleased) {
flingVelocity = myGestureListener.speed;
isReleased = true;
System.out.println("SPEED: " + flingVelocity);
}
else {
block.setTransform(new Vector2((screenWidth - goalPostThickness) / PPM, panLocation / PPM), 0);
}
}
//Creates animated ball
public Body createBall(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set(ballX/PPM,ballY/PPM);
def.fixedRotation = true;
bBody = world.createBody(def);
return bBody;
}
//Sets radius, density, etc.
public void setBallProperties(Body body){
float gbt = screenWidth / 75; //Goal post thickness
float ballRadius = (gbt * 1.5f) / PPM;
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(ballRadius);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 3.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = ball.createFixture(fixtureDef);
circle.dispose();
}
public Body createBlock(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set((screenWidth - (goalPostThickness)) / PPM, 0/PPM);
//def.position.set(-1000, -1000);
def.fixedRotation = true;
def.allowSleep = false;
bBody = world.createBody(def);
return bBody;
}
public void setBlockProperties(Body body){
PolygonShape square = new PolygonShape();
square.setAsBox(goalPostThickness/PPM, (goalWidth/2)/PPM);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = square;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.5f;
// Create our fixture and attach it to the body
body.createFixture(fixtureDef);
square.dispose();
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void attachBlockerShape(Vector2 pos){
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(pos.x, pos.y, goalPostThickness/PPM, (goalWidth/2)/PPM);
game.shape.end();
}
@Override public void dispose(){
box2DDebugRenderer.dispose();
world.dispose();
}
}
java android android-studio libgdx
add a comment |
I am creating a game with libgdx and box2d and right now have created a rectangle body. The body is a "block" which can be flung by the player to try and block a ball.
The problem I am having is that the body is stuck at the position (0, 47.5184) even though that is not the position where it was set. I can even set the postion to something crazy like (-10000, -10000) and it will still render at (0, 47.5184).
The rectangle still works fine with the fling but it simply starts at the wrong spot and cannot be changed.
In my code, I create the body by calling the createBlock and setBlockProperties methods. These Methods are called in the "show" function Also note that the ball used for the game was created the exact same way and works fine.
Code:
public class GameScreen extends ScreenAdapter {
Controller game;
public World world;
public Body ball;
public Body block;
public Box2DDebugRenderer box2DDebugRenderer;
private Matrix4 cameraBox2D;
public MyGestureListener myGestureListener;
//x-axis length for top/bottom bar
private float goalWidth;
//pixels per meter
public float PPM;
//y-axis height for back bar
private float goalHeight;
private float goalPostThickness;
//Screen height and width
private float screenWidth;
private float screenHeight;
//How far down/up posts are from edge of screen
private float goalPostTopOffset;
private float goalPostBottomOffset;
//Center x,y of cannon
private float cannonOriginX; //Variables used for starting poisition of balls
private float cannonOriginY;
//Center x,y of ball
float ballX;
float ballY;
//Velocity of ball
public float velocity = 50;
//Tracks users drag y coord
public float panLocation = 0;
//Velocity of block once the user releases
public float flingVelocity;
//Changes to true when the block is released
public boolean isReleased = false;
public GameScreen (Controller game){
this.game = game;
}
@Override
public void show(){
myGestureListener = new MyGestureListener(game, this);
cameraBox2D = new Matrix4(game.cam.combined);
screenWidth = game.getScreenWidth();
screenHeight = game.getScreenHeight();
PPM = screenHeight / 80;
goalPostTopOffset = screenHeight/7;
goalPostBottomOffset = goalPostTopOffset * 3;
goalHeight = screenHeight - (goalPostTopOffset + goalPostBottomOffset);
goalWidth = screenWidth / 6;
goalPostThickness = screenWidth / 75;
cannonOriginX = goalWidth / 2; //Variables used for starting position of balls
cannonOriginY = (goalPostThickness*5) / 2;
ballX = 0 + cannonOriginX;
ballY = (goalPostBottomOffset - (goalPostBottomOffset / 4)) + cannonOriginY;
world = new World(new Vector2(0, 0f), true);
box2DDebugRenderer = new Box2DDebugRenderer();
//Creates animated ball
ball = createBall();
//Sets radius, density, etc.
setBallProperties(ball);
//Creates block that stops balls
block = createBlock();
//Sets properties
setBlockProperties(block);
}
@Override
public void render(float delta){
//Logic
world.step(1/60f, 6, 2);
//Draw
game.cam.update();
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
box2DDebugRenderer.render(world, game.cam.combined.scl(PPM));
game.shape.setProjectionMatrix(game.cam.combined);
Gdx.input.setInputProcessor(new GestureDetector(myGestureListener));
System.out.println(block.getPosition().y);
System.out.println(block.getPosition().x);
drawNonAnimated();
drawAnimated();
//show()
cameraBox2D = game.cam.combined.cpy(); //Copy the main camera
cameraBox2D.scl(PPM); //Scale the camera projection to the ratio you're using for Box2D
//render()
box2DDebugRenderer.render(world, cameraBox2D);
}
@Override
public void hide(){
}
//draws stationary objects such as goal posts
public void drawNonAnimated(){
//Cannon platform
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, goalWidth/PPM, (goalPostThickness*2)/PPM);
game.shape.end();
//Cannon
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, cannonOriginX/PPM,
cannonOriginY/PPM, goalWidth/PPM, (goalPostThickness*5)/PPM, 1, 1, 45);
game.shape.end();
}
public void drawAnimated(){
//FOR BALL
velocity--;
ball.setLinearVelocity(new Vector2(35,velocity));
Vector2 pos = ball.getPosition();
if (pos.x >= screenWidth/PPM){
ball.setTransform(new Vector2(ballX/PPM, ballY/PPM), 0);
//max 75 min 50
velocity = randInt(50, 75);
}
//Attaching a regular libgdx shape to the position of box2d shape
game.circle.setColor(1, 1, 1, 1);
game.circle.begin(ShapeRenderer.ShapeType.Filled);
game.circle.circle(pos.x*PPM, pos.y*PPM, goalPostThickness * 1.5f);
game.circle.end();
game.cam.update();
blockerMovement();
}
public void blockerMovement(){
//FOR BLOCKER RECTANGLE ANIMATION
Vector2 pos = block.getPosition();
float boundaryLocation = (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM;
//attachBlockerShape(pos);
panLocation = myGestureListener.getPanLocation();
if (isReleased == true){
//Get the velocity as the block is released
//to determine the speed it will continue to go after release
block.setLinearVelocity(0, flingVelocity);
flingVelocity -= 3;
}
else if (myGestureListener.getCheckRelease()|| panLocation/PPM >= boundaryLocation && !isReleased) {
flingVelocity = myGestureListener.speed;
isReleased = true;
System.out.println("SPEED: " + flingVelocity);
}
else {
block.setTransform(new Vector2((screenWidth - goalPostThickness) / PPM, panLocation / PPM), 0);
}
}
//Creates animated ball
public Body createBall(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set(ballX/PPM,ballY/PPM);
def.fixedRotation = true;
bBody = world.createBody(def);
return bBody;
}
//Sets radius, density, etc.
public void setBallProperties(Body body){
float gbt = screenWidth / 75; //Goal post thickness
float ballRadius = (gbt * 1.5f) / PPM;
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(ballRadius);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 3.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = ball.createFixture(fixtureDef);
circle.dispose();
}
public Body createBlock(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set((screenWidth - (goalPostThickness)) / PPM, 0/PPM);
//def.position.set(-1000, -1000);
def.fixedRotation = true;
def.allowSleep = false;
bBody = world.createBody(def);
return bBody;
}
public void setBlockProperties(Body body){
PolygonShape square = new PolygonShape();
square.setAsBox(goalPostThickness/PPM, (goalWidth/2)/PPM);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = square;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.5f;
// Create our fixture and attach it to the body
body.createFixture(fixtureDef);
square.dispose();
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void attachBlockerShape(Vector2 pos){
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(pos.x, pos.y, goalPostThickness/PPM, (goalWidth/2)/PPM);
game.shape.end();
}
@Override public void dispose(){
box2DDebugRenderer.dispose();
world.dispose();
}
}
java android android-studio libgdx
add a comment |
I am creating a game with libgdx and box2d and right now have created a rectangle body. The body is a "block" which can be flung by the player to try and block a ball.
The problem I am having is that the body is stuck at the position (0, 47.5184) even though that is not the position where it was set. I can even set the postion to something crazy like (-10000, -10000) and it will still render at (0, 47.5184).
The rectangle still works fine with the fling but it simply starts at the wrong spot and cannot be changed.
In my code, I create the body by calling the createBlock and setBlockProperties methods. These Methods are called in the "show" function Also note that the ball used for the game was created the exact same way and works fine.
Code:
public class GameScreen extends ScreenAdapter {
Controller game;
public World world;
public Body ball;
public Body block;
public Box2DDebugRenderer box2DDebugRenderer;
private Matrix4 cameraBox2D;
public MyGestureListener myGestureListener;
//x-axis length for top/bottom bar
private float goalWidth;
//pixels per meter
public float PPM;
//y-axis height for back bar
private float goalHeight;
private float goalPostThickness;
//Screen height and width
private float screenWidth;
private float screenHeight;
//How far down/up posts are from edge of screen
private float goalPostTopOffset;
private float goalPostBottomOffset;
//Center x,y of cannon
private float cannonOriginX; //Variables used for starting poisition of balls
private float cannonOriginY;
//Center x,y of ball
float ballX;
float ballY;
//Velocity of ball
public float velocity = 50;
//Tracks users drag y coord
public float panLocation = 0;
//Velocity of block once the user releases
public float flingVelocity;
//Changes to true when the block is released
public boolean isReleased = false;
public GameScreen (Controller game){
this.game = game;
}
@Override
public void show(){
myGestureListener = new MyGestureListener(game, this);
cameraBox2D = new Matrix4(game.cam.combined);
screenWidth = game.getScreenWidth();
screenHeight = game.getScreenHeight();
PPM = screenHeight / 80;
goalPostTopOffset = screenHeight/7;
goalPostBottomOffset = goalPostTopOffset * 3;
goalHeight = screenHeight - (goalPostTopOffset + goalPostBottomOffset);
goalWidth = screenWidth / 6;
goalPostThickness = screenWidth / 75;
cannonOriginX = goalWidth / 2; //Variables used for starting position of balls
cannonOriginY = (goalPostThickness*5) / 2;
ballX = 0 + cannonOriginX;
ballY = (goalPostBottomOffset - (goalPostBottomOffset / 4)) + cannonOriginY;
world = new World(new Vector2(0, 0f), true);
box2DDebugRenderer = new Box2DDebugRenderer();
//Creates animated ball
ball = createBall();
//Sets radius, density, etc.
setBallProperties(ball);
//Creates block that stops balls
block = createBlock();
//Sets properties
setBlockProperties(block);
}
@Override
public void render(float delta){
//Logic
world.step(1/60f, 6, 2);
//Draw
game.cam.update();
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
box2DDebugRenderer.render(world, game.cam.combined.scl(PPM));
game.shape.setProjectionMatrix(game.cam.combined);
Gdx.input.setInputProcessor(new GestureDetector(myGestureListener));
System.out.println(block.getPosition().y);
System.out.println(block.getPosition().x);
drawNonAnimated();
drawAnimated();
//show()
cameraBox2D = game.cam.combined.cpy(); //Copy the main camera
cameraBox2D.scl(PPM); //Scale the camera projection to the ratio you're using for Box2D
//render()
box2DDebugRenderer.render(world, cameraBox2D);
}
@Override
public void hide(){
}
//draws stationary objects such as goal posts
public void drawNonAnimated(){
//Cannon platform
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, goalWidth/PPM, (goalPostThickness*2)/PPM);
game.shape.end();
//Cannon
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, cannonOriginX/PPM,
cannonOriginY/PPM, goalWidth/PPM, (goalPostThickness*5)/PPM, 1, 1, 45);
game.shape.end();
}
public void drawAnimated(){
//FOR BALL
velocity--;
ball.setLinearVelocity(new Vector2(35,velocity));
Vector2 pos = ball.getPosition();
if (pos.x >= screenWidth/PPM){
ball.setTransform(new Vector2(ballX/PPM, ballY/PPM), 0);
//max 75 min 50
velocity = randInt(50, 75);
}
//Attaching a regular libgdx shape to the position of box2d shape
game.circle.setColor(1, 1, 1, 1);
game.circle.begin(ShapeRenderer.ShapeType.Filled);
game.circle.circle(pos.x*PPM, pos.y*PPM, goalPostThickness * 1.5f);
game.circle.end();
game.cam.update();
blockerMovement();
}
public void blockerMovement(){
//FOR BLOCKER RECTANGLE ANIMATION
Vector2 pos = block.getPosition();
float boundaryLocation = (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM;
//attachBlockerShape(pos);
panLocation = myGestureListener.getPanLocation();
if (isReleased == true){
//Get the velocity as the block is released
//to determine the speed it will continue to go after release
block.setLinearVelocity(0, flingVelocity);
flingVelocity -= 3;
}
else if (myGestureListener.getCheckRelease()|| panLocation/PPM >= boundaryLocation && !isReleased) {
flingVelocity = myGestureListener.speed;
isReleased = true;
System.out.println("SPEED: " + flingVelocity);
}
else {
block.setTransform(new Vector2((screenWidth - goalPostThickness) / PPM, panLocation / PPM), 0);
}
}
//Creates animated ball
public Body createBall(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set(ballX/PPM,ballY/PPM);
def.fixedRotation = true;
bBody = world.createBody(def);
return bBody;
}
//Sets radius, density, etc.
public void setBallProperties(Body body){
float gbt = screenWidth / 75; //Goal post thickness
float ballRadius = (gbt * 1.5f) / PPM;
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(ballRadius);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 3.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = ball.createFixture(fixtureDef);
circle.dispose();
}
public Body createBlock(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set((screenWidth - (goalPostThickness)) / PPM, 0/PPM);
//def.position.set(-1000, -1000);
def.fixedRotation = true;
def.allowSleep = false;
bBody = world.createBody(def);
return bBody;
}
public void setBlockProperties(Body body){
PolygonShape square = new PolygonShape();
square.setAsBox(goalPostThickness/PPM, (goalWidth/2)/PPM);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = square;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.5f;
// Create our fixture and attach it to the body
body.createFixture(fixtureDef);
square.dispose();
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void attachBlockerShape(Vector2 pos){
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(pos.x, pos.y, goalPostThickness/PPM, (goalWidth/2)/PPM);
game.shape.end();
}
@Override public void dispose(){
box2DDebugRenderer.dispose();
world.dispose();
}
}
java android android-studio libgdx
I am creating a game with libgdx and box2d and right now have created a rectangle body. The body is a "block" which can be flung by the player to try and block a ball.
The problem I am having is that the body is stuck at the position (0, 47.5184) even though that is not the position where it was set. I can even set the postion to something crazy like (-10000, -10000) and it will still render at (0, 47.5184).
The rectangle still works fine with the fling but it simply starts at the wrong spot and cannot be changed.
In my code, I create the body by calling the createBlock and setBlockProperties methods. These Methods are called in the "show" function Also note that the ball used for the game was created the exact same way and works fine.
Code:
public class GameScreen extends ScreenAdapter {
Controller game;
public World world;
public Body ball;
public Body block;
public Box2DDebugRenderer box2DDebugRenderer;
private Matrix4 cameraBox2D;
public MyGestureListener myGestureListener;
//x-axis length for top/bottom bar
private float goalWidth;
//pixels per meter
public float PPM;
//y-axis height for back bar
private float goalHeight;
private float goalPostThickness;
//Screen height and width
private float screenWidth;
private float screenHeight;
//How far down/up posts are from edge of screen
private float goalPostTopOffset;
private float goalPostBottomOffset;
//Center x,y of cannon
private float cannonOriginX; //Variables used for starting poisition of balls
private float cannonOriginY;
//Center x,y of ball
float ballX;
float ballY;
//Velocity of ball
public float velocity = 50;
//Tracks users drag y coord
public float panLocation = 0;
//Velocity of block once the user releases
public float flingVelocity;
//Changes to true when the block is released
public boolean isReleased = false;
public GameScreen (Controller game){
this.game = game;
}
@Override
public void show(){
myGestureListener = new MyGestureListener(game, this);
cameraBox2D = new Matrix4(game.cam.combined);
screenWidth = game.getScreenWidth();
screenHeight = game.getScreenHeight();
PPM = screenHeight / 80;
goalPostTopOffset = screenHeight/7;
goalPostBottomOffset = goalPostTopOffset * 3;
goalHeight = screenHeight - (goalPostTopOffset + goalPostBottomOffset);
goalWidth = screenWidth / 6;
goalPostThickness = screenWidth / 75;
cannonOriginX = goalWidth / 2; //Variables used for starting position of balls
cannonOriginY = (goalPostThickness*5) / 2;
ballX = 0 + cannonOriginX;
ballY = (goalPostBottomOffset - (goalPostBottomOffset / 4)) + cannonOriginY;
world = new World(new Vector2(0, 0f), true);
box2DDebugRenderer = new Box2DDebugRenderer();
//Creates animated ball
ball = createBall();
//Sets radius, density, etc.
setBallProperties(ball);
//Creates block that stops balls
block = createBlock();
//Sets properties
setBlockProperties(block);
}
@Override
public void render(float delta){
//Logic
world.step(1/60f, 6, 2);
//Draw
game.cam.update();
Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
box2DDebugRenderer.render(world, game.cam.combined.scl(PPM));
game.shape.setProjectionMatrix(game.cam.combined);
Gdx.input.setInputProcessor(new GestureDetector(myGestureListener));
System.out.println(block.getPosition().y);
System.out.println(block.getPosition().x);
drawNonAnimated();
drawAnimated();
//show()
cameraBox2D = game.cam.combined.cpy(); //Copy the main camera
cameraBox2D.scl(PPM); //Scale the camera projection to the ratio you're using for Box2D
//render()
box2DDebugRenderer.render(world, cameraBox2D);
}
@Override
public void hide(){
}
//draws stationary objects such as goal posts
public void drawNonAnimated(){
//Cannon platform
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, goalWidth/PPM, (goalPostThickness*2)/PPM);
game.shape.end();
//Cannon
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(0, (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM, cannonOriginX/PPM,
cannonOriginY/PPM, goalWidth/PPM, (goalPostThickness*5)/PPM, 1, 1, 45);
game.shape.end();
}
public void drawAnimated(){
//FOR BALL
velocity--;
ball.setLinearVelocity(new Vector2(35,velocity));
Vector2 pos = ball.getPosition();
if (pos.x >= screenWidth/PPM){
ball.setTransform(new Vector2(ballX/PPM, ballY/PPM), 0);
//max 75 min 50
velocity = randInt(50, 75);
}
//Attaching a regular libgdx shape to the position of box2d shape
game.circle.setColor(1, 1, 1, 1);
game.circle.begin(ShapeRenderer.ShapeType.Filled);
game.circle.circle(pos.x*PPM, pos.y*PPM, goalPostThickness * 1.5f);
game.circle.end();
game.cam.update();
blockerMovement();
}
public void blockerMovement(){
//FOR BLOCKER RECTANGLE ANIMATION
Vector2 pos = block.getPosition();
float boundaryLocation = (goalPostBottomOffset - (goalPostBottomOffset / 4))/PPM;
//attachBlockerShape(pos);
panLocation = myGestureListener.getPanLocation();
if (isReleased == true){
//Get the velocity as the block is released
//to determine the speed it will continue to go after release
block.setLinearVelocity(0, flingVelocity);
flingVelocity -= 3;
}
else if (myGestureListener.getCheckRelease()|| panLocation/PPM >= boundaryLocation && !isReleased) {
flingVelocity = myGestureListener.speed;
isReleased = true;
System.out.println("SPEED: " + flingVelocity);
}
else {
block.setTransform(new Vector2((screenWidth - goalPostThickness) / PPM, panLocation / PPM), 0);
}
}
//Creates animated ball
public Body createBall(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set(ballX/PPM,ballY/PPM);
def.fixedRotation = true;
bBody = world.createBody(def);
return bBody;
}
//Sets radius, density, etc.
public void setBallProperties(Body body){
float gbt = screenWidth / 75; //Goal post thickness
float ballRadius = (gbt * 1.5f) / PPM;
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(ballRadius);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 3.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = ball.createFixture(fixtureDef);
circle.dispose();
}
public Body createBlock(){
Body bBody;
BodyDef def = new BodyDef();
def.type = BodyDef.BodyType.DynamicBody;
def.position.set((screenWidth - (goalPostThickness)) / PPM, 0/PPM);
//def.position.set(-1000, -1000);
def.fixedRotation = true;
def.allowSleep = false;
bBody = world.createBody(def);
return bBody;
}
public void setBlockProperties(Body body){
PolygonShape square = new PolygonShape();
square.setAsBox(goalPostThickness/PPM, (goalWidth/2)/PPM);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = square;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution = 0.5f;
// Create our fixture and attach it to the body
body.createFixture(fixtureDef);
square.dispose();
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void attachBlockerShape(Vector2 pos){
game.shape.setColor(1, 1, 1, 1);
game.shape.begin(ShapeRenderer.ShapeType.Filled);
game.shape.rect(pos.x, pos.y, goalPostThickness/PPM, (goalWidth/2)/PPM);
game.shape.end();
}
@Override public void dispose(){
box2DDebugRenderer.dispose();
world.dispose();
}
}
java android android-studio libgdx
java android android-studio libgdx
asked Dec 29 '18 at 2:27
Nick HudsonNick Hudson
45
45
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53966196%2flibgdx-box2d-body-stuck%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53966196%2flibgdx-box2d-body-stuck%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown