FitViewPort Android libGDX - java

How can I use this ViewPort to fit the screen to the many Android devices as I can? What's the best option?.
This is my game.
GameScreen.java
public class GameScreen extends AbstractScreen {
private SpriteBatch batch;
private Texture texture;
private Paddle Lpaddle, Rpaddle;
private Ball ball;
private BitmapFont font;
private int puntuacion, puntuacionMaxima;
private Preferences preferencias;
private Music music;
private Sound sonidoex;
public GameScreen(Main main) {
super(main);
preferencias = Gdx.app.getPreferences("PuntuacionAppPoints");
puntuacionMaxima = preferencias.getInteger("puntuacionMaxima");
music =Gdx.audio.newMusic(Gdx.files.internal("bgmusic.mp3"));
music.play();
music.setVolume((float) 0.3);
music.setLooping(true);
sonidoex = Gdx.audio.newSound(Gdx.files.internal("explosion5.wav"));
}
public void show(){
batch = main.getBatch();
texture = new Texture(Gdx.files.internal("spacebg.png"));
Texture texturaBola = new Texture(Gdx.files.internal("bola.png"));
ball = new Ball(Gdx.graphics.getWidth() / 2 - texturaBola.getWidth() / 2, Gdx.graphics.getHeight() / 2 - texturaBola.getHeight() / 2);
Texture texturaPala= new Texture(Gdx.files.internal("pala.png"));
Lpaddle = new LeftPaddle(80, Gdx.graphics.getHeight()/2 -texturaPala.getHeight() /2);
Rpaddle = new RightPaddle(Gdx.graphics.getWidth() -100, Gdx.graphics.getHeight()/2 - texturaPala.getHeight() /2, ball);
font = new BitmapFont(Gdx.files.internal("pointsfont.tf.fnt"), Gdx.files.internal("pointsfont.tf.png"), false);
puntuacion = 0;
}
public void render(float delta){
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updatePuntuacion();
Lpaddle.update();
Rpaddle.update();
ball.update(Lpaddle, Rpaddle);
batch.begin();
batch.draw(texture, 0, 0,texture.getWidth(), texture.getHeight());
ball.draw(batch);
Lpaddle.draw(batch);
Rpaddle.draw(batch);
font.draw(batch, "Points: " + Integer.toString(puntuacion), Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
font.draw(batch, "High score: " + Integer.toString(puntuacionMaxima),Gdx.graphics.getWidth() - Gdx.graphics.getWidth() / 4 ,Gdx.graphics.getHeight() - 5);
batch.end();
}
private void updatePuntuacion(){
if(ball.getBordes().overlaps(Lpaddle.getBordes())) {
puntuacion = puntuacion + 1;
if(puntuacion > puntuacionMaxima)
puntuacionMaxima = puntuacion;
}
if(ball.getBordes().x <= 0)
sonidoex.play();
if(ball.getBordes().x <= 0)
puntuacion =0;
if(ball.getBordes().x <=0)
Gdx.input.vibrate(1000);
if(ball.getBordes().x <=0)
Screens.juego.setScreen(Screens.MAINSCREEN);
ball.comprobarPosicionBola();
}
public void hide(){
font.dispose();
texture.dispose();
}
#Override
public void dispose(){
preferencias.putInteger("puntuacionMaxima", puntuacionMaxima);
preferencias.flush();
}
public void resize(int width, int height){
float widthImage = texture.getWidth();
float heightImage = texture.getHeight();
float r = heightImage / widthImage;
if(heightImage > height) {
heightImage = height;
widthImage = heightImage / r;
}
if(widthImage > width) {
widthImage = width;
heightImage = widthImage * r;
}
}
}

Related

How do I make multiple balls drop from the top?

public class MovingBagView extends View {
private Bitmap bag[] = new Bitmap[2];
private int bagX;
private int bagY = 1000;
private int bagSpeed;
private Boolean touch = false;
private int canvasWidth, canvasHeight;
private int yellowX = 500, yellowY, yellowSpeed = -16;
private Paint yellowPaint = new Paint();
private int score;
private Bitmap backgroundImage;
private Paint scorePaint = new Paint();
private Bitmap life[] = new Bitmap[2];
public MovingBagView(Context context) {
super(context);
bag[0] = BitmapFactory.decodeResource(getResources(), R.drawable.bag1);
bag[1] = BitmapFactory.decodeResource(getResources(), R.drawable.bag2);
backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
yellowPaint.setColor(Color.YELLOW);
yellowPaint.setAntiAlias(false);
scorePaint.setColor(Color.BLACK);
scorePaint.setTextSize(40);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
life[0] = BitmapFactory.decodeResource(getResources(), R.drawable.heart);
life[1] = BitmapFactory.decodeResource(getResources(), R.drawable.heart_grey);
bagX = 10;
score = 0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvasWidth = canvas.getWidth();
canvasHeight = canvas.getHeight();
canvas.drawBitmap(backgroundImage, 0, 0, null);
int minBagX = bag[0].getWidth();
int maxBagX = canvasWidth - bag[0].getWidth() * 2;
bagX = bagX + bagSpeed;
if (bagX < minBagX) {
bagX = minBagX;
}
if (bagX >= maxBagX) {
bagX = maxBagX;
}
bagSpeed = bagSpeed + 2;
if (touch) {
canvas.drawBitmap(bag[1], bagX, bagY, null);
}
else {
canvas.drawBitmap(bag[0], bagX, bagY, null);
}
yellowY = yellowY - yellowSpeed;
if (hitBallChecker(yellowX, yellowY)) {
score = score + 10;
yellowY = -100;
}
if (yellowY < 0) {
yellowY = canvasHeight + 21;
yellowX = (int)Math.floor(Math.random() * (maxBagX - minBagX)) + maxBagX;
}
canvas.drawCircle(yellowX, yellowY, 15, yellowPaint);
canvas.drawText("Score : " + score, 20, 60, scorePaint);
canvas.drawBitmap(life[0], 500, 10, null);
canvas.drawBitmap(life[0], 570, 10, null);
canvas.drawBitmap(life[0], 640, 10, null);
}
public boolean hitBallChecker(int x, int y) {
if (bagY < y && y < (bagY + bag[0].getHeight()) && bagX < x && x < (bagX + bag[0].getWidth())) {
return true;
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touch = true;
bagSpeed = -22;
}
return true;
}
}
I've figured out how to make the balls drop from the top of the screen. The code is supposed to make multiple yellow balls drop from the top of the screen, but only one yellow ball drops. Random yellow balls are supposed to drop from the top, and they drop from different positions. You can see the preview of it below:
To implement this, you should consider creating a custom object Ball
public class Ball{
public int x;
public int y;
public int speed;
public Ball(int x, int y, int speed){
this.x = x;
this.y = y;
this.speed = speed;
}
}
Then you can add multiple Balls in an ArrayList and in the draw() you iterate through every Ball in the array and do what you've been doing to one Ball with each.
for(int i = 0; i < balls.length(); i++){
Ball ball = balls.get(i);
ball.y -= ball.speed;
// check for collisions
// draw ball
}

Libgdx popping noise while playing music

I have this problem where when I play this certain music with libgdx, I start hearing some soft popping noise in the background while the music is played. I have tried some different audio formats but It doesn't help. In my code the music is the "endmusic".
Here is my whole code:
public class WorldScreen implements Screen{
Preferences prefs;
private Texture bgCity;
private Texture bgLoop;
private Texture bgEnd;
private Texture bgFade;
private Texture hud;
public static OrthographicCamera camera;
SpriteBatch batch;
Rectangle player;
Rectangle background;
Rectangle backgroundloop;
public float time = 100;
public float camx = 0;
public float camy = 0;
public static float score = 384400000f;
public static float value = 384400000f;
BitmapFont font;
GestureListenerC controller;
private Music startmusic;
private static Music loopmusic;
private Music endMusic;
public static boolean ending = false;
private int endint;
private String endstring = "";
public WorldScreen(final JetpackGame aa) {
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camx = camera.viewportWidth / 2f;
camy = camera.viewportHeight / 2f;
controller.update();
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(bgCity, background.x, background.y);
batch.draw(bgLoop, backgroundloop.x, backgroundloop.y);
batch.draw(bgEnd, 0, 5360);
if(!ending){
if(camera.position.y >= 5360) camera.position.y = 4096;
}
if(value <= 0) ending = true;
//ENDING
if(ending){
time += 0.1f * Gdx.graphics.getDeltaTime();
startmusic.stop();
loopmusic.stop();
if(time <= 102.75f){
camera.position.y += 0.1 * time;
if(camera.position.y >= 5360) camera.position.y = 4096;
}
if(time >= 102.75f) {
if (camera.position.y >= 4090 && camera.position.y <= 6666)
camera.position.y += 0.1 * time;
}
endMusic.play();
font.setScale(2.0f);
font.draw(batch, "You already finished the game xD", 0,1200);
if(time >= 103.2f)endMusic.stop();
}
Matrix4 normalProjection = new Matrix4().setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.setProjectionMatrix(normalProjection);
batch.draw(hud, 0, 85, Gdx.graphics.getWidth(), 1200);
font.setScale(3.5f);
if(time <=102.5f) {
font.draw(batch, ">Meters to the moon", 10, 1260);
font.draw(batch, ">" + (int)value + "m", 10, 1190);
}
//font.draw(batch,""+time, 100, 100);
//font.draw(batch,""+value, 100,120);
if(time >= 103) {
font.setScale(3.0f);
font.draw(batch, ">"+endstring, 10,1200);
}
if(time >= 104)
batch.draw(bgFade, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
if(value < 0) value = 0;
if(!startmusic.isPlaying()) {
loopmusic.setLooping(true);
loopmusic.play();
}
//RANDOM ENDING GENERATOR
switch(endint){
case 1: endstring = "Now do it again faster!";
break;
case 2: endstring = "What are you doing with your life?!";
break;
case 3: endstring = "Do you want a cookie?";
break;
case 4: endstring = "How many hours did you waste?";
break;
case 5: endstring = "So you have no life?";
break;
case 6: endstring = "Now get out of your room and go outside!";
break;
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
Random rand = new Random();
endint = rand.nextInt(6);
font = new BitmapFont();
font.setColor(Color.GREEN);
Preferences prefs = Gdx.app.getPreferences("My Preferences");
float value = prefs.getFloat("Value", 384400000f);
controller = new GestureListenerC();
GestureDetector gestureDetector = new GestureDetector(20, 0.5f, 2, 0.15f, controller);
Gdx.input.setInputProcessor(gestureDetector);
loopmusic = Gdx.audio.newMusic(Gdx.files.internal("audio/AmbientLoop.ogg"));
startmusic = Gdx.audio.newMusic(Gdx.files.internal("audio/AmbientStart.ogg"));
endMusic = Gdx.audio.newMusic(Gdx.files.internal("audio/Moon.ogg"));
endMusic.setLooping(false);
startmusic.play();
bgCity = new Texture(Gdx.files.internal("img/city_BG.png"));
bgLoop = new Texture(Gdx.files.internal("img/loopBG.png"));
bgEnd = new Texture(Gdx.files.internal("img/endBG.png"));
bgFade = new Texture(Gdx.files.internal("img/fade.png"));
hud = new Texture(Gdx.files.internal("img/Hud.png"));
camera = new OrthographicCamera();
camera.setToOrtho(false, 480,854);
batch = new SpriteBatch();
background = new Rectangle();
background.x = 0;
background.y = 0;
background.width = 479;
background.height = 4096;
backgroundloop = new Rectangle();
backgroundloop.x = 0;
backgroundloop.y = 4096;
backgroundloop.width = 512;
backgroundloop.height = 1024;
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
prefs.putFloat("Value", value);
prefs.flush();
batch.dispose();
font.dispose();
bgCity.dispose();
bgLoop.dispose();
bgEnd.dispose();
bgFade.dispose();
hud.dispose();
loopmusic.dispose();
startmusic.dispose();
endMusic.dispose();
}
}

libgdx bind multiple part textures and stuff

I am developing an off road game, and I am new to libgdx.
I made a car, with only 3 parts: chassis, rear & front wheel. I got a "Zoomable" camera bind with chassis, chassis connected to wheels with Wheel Joint.
Chassis works fine with texture but not wheels.
Here's the problems:
I can't figure out how to calculate the √(correct) vector2 of wheels to put it in the [Sprite.setPosition] method
How to make my car faster cause it never >94
Focus.java
public class Focus extends InputAdapter {
private Body chassis, rearWheel, frontWheel;
private WheelJoint leftAxis, rightAxis;
private float speed = 90f;
private Sprite spriteChassis, spriteRearWheel, spriteFrontWheel;
private float xOffSet = 5f;
private float yOffSet = -2f;
private float rwOffSet = 0;
private float fwOffSet = 0;
private float rwOffSetY = 0;
private float fwOffSetY = 0;
public float getOffSetX(){ return xOffSet; }
public float getOffSetY(){ return yOffSet; }
public Focus(World world, FixtureDef chassisFixtureDef, FixtureDef wheelFixtureDef, float x, float y) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(x,y);
bodyDef.gravityScale = 1;
float width = 5.333f;
float height = 1.933f;
BodyEditorLoader loader = new BodyEditorLoader(Gdx.files.internal("data/focus.json"));
chassis = world.createBody(bodyDef);
loader.attachFixture(chassis, "focus", chassisFixtureDef, width);
String imgpath = loader.getImagePath("focus");
chassis.createFixture(chassisFixtureDef);
chassis.setGravityScale(1.2f);
spriteChassis = new Sprite(new Texture(imgpath));
spriteRearWheel = new Sprite(new Texture("tires.png"));
spriteFrontWheel = new Sprite(new Texture("tires.png"));
// Wheels
CircleShape wheelShape = new CircleShape();
wheelShape.setRadius(height / 6f);
wheelFixtureDef.shape = wheelShape;
rearWheel = world.createBody(bodyDef);
rearWheel.createFixture(wheelFixtureDef);
frontWheel = world.createBody(bodyDef);
frontWheel.createFixture(wheelFixtureDef);
// Axels
WheelJointDef axisDef = new WheelJointDef();
axisDef.bodyA = chassis;
axisDef.bodyB = rearWheel;
rwOffSet = wheelShape.getRadius()*3.3f;
axisDef.localAnchorA.x = rwOffSet;
rwOffSetY = height/10.5f;
axisDef.localAnchorA.y = rwOffSetY;
axisDef.frequencyHz = chassisFixtureDef.density;
axisDef.localAxisA.set(Vector2.Y);
axisDef.maxMotorTorque = chassisFixtureDef.density * 24.5f;
leftAxis = (WheelJoint) world.createJoint(axisDef);
// right
// Axels
WheelJointDef axisDef2 = new WheelJointDef();
axisDef2.bodyA = chassis;
axisDef2.bodyB = frontWheel;
axisDef2.localAnchorA.set(width, 0);
axisDef2.frequencyHz = chassisFixtureDef.density;
axisDef2.localAxisA.set(Vector2.Y);
fwOffSet = width-wheelShape.getRadius()*3.f;
axisDef2.localAnchorA.x = fwOffSet;
fwOffSetY = height/9f;
axisDef.localAnchorA.y = fwOffSetY;
axisDef2.maxMotorTorque = chassisFixtureDef.density * 24.5f;
rightAxis = (WheelJoint) world.createJoint(axisDef2);
}
#Override
public boolean keyDown(int keycode) {
switch(keycode) {
case Input.Keys.W:
leftAxis.enableMotor(false);
rightAxis.enableMotor(true);
rightAxis.setMotorSpeed(-speed);
break;
case Input.Keys.S:
leftAxis.enableMotor(false);
rightAxis.enableMotor(true);
rightAxis.setMotorSpeed(speed);
break;
case Input.Keys.SPACE:
leftAxis.enableMotor(true);
leftAxis.setMotorSpeed(0);
rightAxis.enableMotor(true);
rightAxis.setMotorSpeed(0);
break;
}
return true;
}
#Override
public boolean keyUp(int keycode) {
switch(keycode) {
case Input.Keys.SPACE:
case Input.Keys.W:
case Input.Keys.S:
leftAxis.enableMotor(false);
rightAxis.enableMotor(false);
break;
}
return true;
}
public Sprite getSpriteChassis(){ return spriteChassis; }
public Sprite getSpriteRearWheel() { return spriteRearWheel; }
public Sprite getSpriteFrontWheel() { return spriteFrontWheel; }
public Body getChassis() { return chassis; }
public Body getFrontWheel() { return frontWheel; }
public Body getRearWheel() { return rearWheel; }
}
SmallHill.java (Screen)
public class SmallHill implements Screen {
private final float PIXELS_PER_METER = 15f; // how many pixels to a meter
private final float TIME_STEP = 1 / 60f; // 60 fps
private final float SPEED = 1 / 60f; // speed constant
private final float MIN_ZOOM = .25f; // How far in should we be able to zoom
private final float ANGULAR_MOMENTUM = .5f;
private final int VELOCITY_ITERATIONS = 8; // copied from box2d example
private final int POSITION_ITERATIONS = 3; // copied from box2d example
private World world;
private Box2DDebugRenderer debugRenderer;
private OrthographicCamera camera;
private Body ball;
private Focus focus;
private BitmapFont font;
private SpriteBatch batch;
private Texture texture;
#Override
public void show() {
batch = new SpriteBatch();
font = new BitmapFont();
font.setColor(Color.RED);
world = new World(new Vector2(0, -9.81f), true);
debugRenderer = new Box2DDebugRenderer();
camera = new OrthographicCamera();
camera.zoom = 1f;
BodyDef bodyDef = new BodyDef();
// Shape
ChainShape groundShape = new ChainShape();
groundShape.createChain(new Vector2[] {new Vector2(-1,24),new Vector2(0,14),new Vector2(25,14),new Vector2(50,10),new Vector2(100,5),new Vector2(150,12),new Vector2(155,10), new Vector2(200,22),new Vector2(225,22),new Vector2(226,22.15f),new Vector2(227,22),new Vector2(229,22.25f),new Vector2(350,22),new Vector2(385,24),new Vector2(389,25),new Vector2(390,24),new Vector2(395,25),new Vector2(398,24),new Vector2(400,25),new Vector2(401,48) });
CircleShape ballShape = new CircleShape();
ballShape.setRadius(1f);
ballShape.setPosition(new Vector2(-10, 16));
// Fixture
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = groundShape;
fixtureDef.friction = .8f;
fixtureDef.restitution = 0;
world.createBody(bodyDef).createFixture(fixtureDef);
fixtureDef.shape = ballShape;
fixtureDef.friction = 0.9f;
fixtureDef.restitution = .3f;
fixtureDef.density = 3;
bodyDef.type = BodyType.DynamicBody;
fixtureDef.density = 5;
fixtureDef.friction = .4f;
fixtureDef.restitution = .1f;
FixtureDef wheelFixtureDef = new FixtureDef();
wheelFixtureDef.density = fixtureDef.density ;
wheelFixtureDef.friction = 2;
wheelFixtureDef.restitution = .7f;
focus = new Focus(world, fixtureDef, wheelFixtureDef, 50, 14);
wheelFixtureDef.shape.dispose();
fixtureDef.shape.dispose();
Gdx.input.setInputProcessor(new InputMultiplexer(new InputController() {
#Override
public boolean keyDown(int keycode) {
switch(keycode) {
case Input.Keys.ESCAPE:
dispose();
break;
case Input.Keys.R:
camera.zoom = 1;
break;
case Input.Keys.PLUS:
camera.zoom = 10;
break;
case Input.Keys.MINUS:
camera.zoom = 1;
break;
}
return false;
}
#Override
public boolean scrolled(int amount) {
if(amount == -1 && camera.zoom <= MIN_ZOOM) {
camera.zoom = MIN_ZOOM;
} else {
camera.zoom += amount / PIXELS_PER_METER;
}
return false;
}
},focus));
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
camera.position.set(focus.getChassis().getWorldCenter().x,focus.getChassis().getWorldCenter().y,0);
camera.update();
String x;
WheelJoint wj = (WheelJoint) focus.getChassis().getJointList().get(0).joint;
x = (int)Math.abs(wj.getJointSpeed())+"";
batch.begin();
font.draw(batch, x, 20, 20);
focus.getSpriteChassis().setPosition((Gdx.graphics.getWidth() / 2 - focus.getSpriteChassis().getWidth() / 2) + focus.getOffSetX(), (Gdx.graphics.getHeight() / 2 - focus.getSpriteChassis().getHeight() / 2) + focus.getOffSetY());
focus.getSpriteChassis().setRotation(focus.getChassis().getAngle() * MathUtils.radiansToDegrees);
focus.getSpriteChassis().setScale(1/camera.zoom);
focus.getSpriteChassis().draw(batch);
focus.getSpriteRearWheel().setPosition((Gdx.graphics.getWidth() / 2 - focus.getSpriteChassis().getWidth() / 2) , (Gdx.graphics.getHeight() / 2 - focus.getSpriteChassis().getHeight() / 2) );
focus.getSpriteFrontWheel().setPosition((Gdx.graphics.getWidth() / 2 - focus.getSpriteChassis().getWidth() / 2) , (Gdx.graphics.getHeight() / 2 - focus.getSpriteChassis().getHeight() / 2) );
//focus.getSpriteRearWheel().setPosition((Gdx.graphics.getWidth() / 2 - focus.getSpriteChassis().getWidth() / 2) + focus.getRwOffSet()*PIXELS_PER_METER*(1/camera.zoom), (Gdx.graphics.getHeight() / 2 - focus.getSpriteChassis().getHeight() / 2) + focus.getRwOffSetY()*PIXELS_PER_METER*(1/camera.zoom) );
//focus.getSpriteFrontWheel().setPosition((Gdx.graphics.getWidth() / 2 - focus.getSpriteChassis().getWidth() / 2)+ focus.getFwOffSet()*PIXELS_PER_METER*(1/camera.zoom) , (Gdx.graphics.getHeight() / 2 - focus.getSpriteChassis().getHeight() / 2) + focus.getFwOffSetY()*PIXELS_PER_METER*(1/camera.zoom));
focus.getSpriteRearWheel().setRotation(focus.getRearWheel().getAngle() * MathUtils.radiansToDegrees);
focus.getSpriteFrontWheel().setRotation(focus.getFrontWheel().getAngle() * MathUtils.radiansToDegrees);
focus.getSpriteRearWheel().setScale(1 / camera.zoom);
focus.getSpriteRearWheel().draw(batch);
focus.getSpriteFrontWheel().setScale(1 / camera.zoom);
focus.getSpriteFrontWheel().draw(batch);
batch.end();
debugRenderer.render(world, camera.combined);
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width / PIXELS_PER_METER;
camera.viewportHeight = height / PIXELS_PER_METER;
}
#Override
public void hide() { dispose(); }
#Override
public void pause() { }
#Override
public void resume() { }
#Override
public void dispose() {
world.dispose();
debugRenderer.dispose();
batch.dispose();
font.dispose();
}
}
Can anyone help me understand? many thanks !!!
Box2D has a speed limit, which is about 2.0 units/timestep.
So if you step 60 times / second, you can move 2 * 60 = 120 units/second.
To increase the maximum speed you can decrease the timestep i.e. increase the number of steps/second.
If you, for example, increase it to 30, you can move up to 2 * 120 = 240 units/second.
Also make sure, that you are using meters as your unit. Box2D has been created with kg, meters and seconds in mind, so you should also use those units.

libgdx making my physics upside down?

For some reason when I use the same code in a previous physics test without libgdx it works fine. But with libgdx it thinks the ground is in the sky.
package com.me.randomtests;
import com.badlogic.gdx.ApplicationListener;
import...
public class Randomtest implements ApplicationListener {
ShapeRenderer SR;
int x = 100, y = 100, radius = 10;
double deltax = 0, deltay = 0, gravity = 15, energyloss = .65, dt = .2;
#Override
public void create() {
SR=new ShapeRenderer();
}
#Override
public void dispose() {
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
SR.begin(ShapeType.FilledCircle);
SR.filledCircle(x, y, radius);
SR.setColor(Color.BLUE);
SR.end();
Update();
}
public void Update(){
System.out.println(y);
if(x + deltax > Gdx.graphics.getWidth() - radius -1 ){
x = Gdx.graphics.getWidth() - radius - 1;
deltax = - deltax;
}else if(x + deltax < 0 + radius){
x = 0+radius;
deltax= - deltax;
}else{
x += deltax;
}
if(y>Gdx.graphics.getHeight() - radius - 1){
y = Gdx.graphics.getHeight() - radius - 1;
deltay *=.9;
deltay = -deltay;
}else{
//vel formuka
deltay += gravity *dt;
//pos formula
y +=deltay*dt + .5*gravity*dt*dt;
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
what is my problem here? Also does anyone know why 0 is at the bottom with libgdx?

Collision between ball and rectangles, LibGDX

I'm trying to make a reflection of the ball from the walls and rectangles. With walls this code works fine, but with rectangles I have problems. It just reflect to the left and then to the right every 1 pixel until collision ends. Example:
what am I doing wrong?
Ball:
public class Ball {
private int DEFAULT_SPEED = 2;
private double angle;
private static final int PI = 180;
private int mAngle;
private Rectangle bounds;
private Circle circle;
private Vector2 position;
Player player;
Block block;
public Ball(Vector2 position, Block block) {
this.position = position;
this.block = block;
mAngle = getRandomAngle();
bounds = new Rectangle(position.x, position.y, Gdx.graphics.getWidth() / 20, Gdx.graphics.getHeight() / 15);
circle = new Circle(position.x, position.y, Gdx.graphics.getWidth() / 26);
}
// update moves
public void update() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
bounds.set(position.x, position.y, bounds.getWidth(), bounds.getHeight());
circle.set(position.x, position.y, circle.radius);
double angle = Math.toRadians(mAngle);
position.x += 2*(int)Math.round(DEFAULT_SPEED * Math.cos(angle));
position.y += 2*(int)Math.round(DEFAULT_SPEED * Math.sin(angle));
if(position.x >= Gdx.graphics.getWidth() - circle.radius){
reflectVertical();
} else if(position.x <= 0){
reflectVertical();
}
if(position.y >= Gdx.graphics.getHeight()- circle.radius){
reflectHorizontal();
} else if(position.y <= 0){
reflectHorizontal();
} else if(bounds.overlaps(block.getBounds())){
reflectHorizontal();
System.out.println("BLOCK");
}
}
// update |
public void reflectVertical(){
if(mAngle > 0 && mAngle < PI){
mAngle = PI - mAngle;
} else {
mAngle = 3 * PI - mAngle;
}
}
// update -
public void reflectHorizontal(){
mAngle = 2 * PI - mAngle;
}
private int getRandomAngle() {
Random rnd = new Random(System.currentTimeMillis());
return rnd.nextInt(1) * PI + PI / 2 + rnd.nextInt(15) + 285;
}
public double getAngle() {
return angle;
}
public void setAngle(double angle) {
this.angle = angle;
}
public int getDEFAULT_SPEED() {
return DEFAULT_SPEED;
}
public void setDEFAULT_SPEED(int dEFAULT_SPEED) {
DEFAULT_SPEED = dEFAULT_SPEED;
}
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public Rectangle getBounds() {
return bounds;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public Vector2 getPosition() {
return position;
}
}
Rectangle:
public class Block {
private Rectangle bounds;
private Vector2 position;
public Block(Vector2 position) {
this.position = position;
bounds = new Rectangle(position.x, position.y, Gdx.graphics.getWidth() / 8, Gdx.graphics.getHeight() / 12);
}
public void update() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
bounds.set(position.x, position.y, bounds.getWidth(), bounds.getHeight());
}
public Rectangle getBounds() {
return bounds;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public Vector2 getPosition() {
return position;
}
}
Replace
bounds.set(position.x, position.y, bounds.getWidth(), bounds.getHeight());
with
bounds.set(position.x - bounds.getWidth() / 2,
position.y - bounds.getHeight() / 2,
bounds.getWidth(), bounds.getHeight());
Also,
bounds.set(position.x, position.y, bounds.getWidth(), bounds.getHeight());
circle.set(position.x, position.y, circle.radius);
should be at the end of update method. This should solve the issue.
Hope this helps.

Categories

Resources