Libgdx popping noise while playing music - java

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

Related

How do I animate my characters' movement in a LibGDX isometric RPG?

I want my characters move once to nearby tiles with one key press, and be rendered within the movements, so their movements would be animated. But when I tried this, they just teleport to the target tiles with some weird shakings. I think the problem is the ptime/delta variable didn't work as I thought, but I can't tell why. Even when I set the condition to "if(ptime >= 200f)", those movements are the same.
Here are my codes:
public class Player{
private Texture img;
public Vector2 worldPos;
public Vector2 tileMapPos;
private float time;
private float ptime;
private boolean isArrived;
private float nowx, nowy;
public Player() {
img = new Texture("filepath")
worldPos = new Vector2(1, 164);
tileMapPos = new Vector2(9, 9);
time = 0.5f;
ptime = 0f;
isArrived = false;
}
public void render(SpriteBatch batch) {
batch.draw(img, worldPos.x, worldPos.y, 32, 32);
}
public void update(SpriteBatch batch, float delta) {
time += delta;
if (time >= 0.5f) {
move(batch, delta);
time = 0f;
}
private void move(SpriteBatch batch, float delta) {
if (Gdx.input.isKeyJustPressed(Input.Keys.W)) {
ptime += delta;
isArrived = false;
nowx = worldPos.x;
nowy = worldPos.y;
if (ptime >= 0.02f) {
worldPos.x -= 2;
worldPos.y += 1;
ptime = 0f;
}
if ((nowx - worldPos.x) == 16 && (worldPos.y - nowy) == 8) {
isArrived = true;
}
tileMapPos.x += 1;
} else if (Gdx.input.isKeyJustPressed(Input.Keys.A)) {
///
} else if (Gdx.input.isKeyJustPressed(Input.Keys.S)) {
///
} else if (Gdx.input.isKeyJustPressed(Input.Keys.D)) {
///
}
}
}
And this is in the game screen class:
batch.begin();
map.render(batch, delta);
player.update(batch, delta);
player.render(batch);
batch.end();

Why doesn't libgdx button work every time?

I made a button, witch stops the game. The is a menu, where you can continue the game. But if the cam moves with the player, the button doesn't work any more. You can see it, but if you click on it nothing happens. If you come back to the "start position" of the cam, the button works again. But the InputProcessor is always the stage with the button.
public class PlayState extends State {
//Objects
private final GameStateManager gameStateManager;
private final State me;
private EntityManager entityManager;
private Player player;
private Texture background;
private Texture filter;
private BitmapFont font;
private Sound click, boost;
private Drug drug;
private Border border;
private House house;
//Constants
public static final int FIELD_SIZE_HEIGHT = 1000;
public static final int FIELD_SIZE_WIDTH = 500;
//Variables
private int collectedDrugs;
private boolean pause, renderLost;
private boolean boostSound;
//Button pause
private Stage stage;
private ImageButton button;
private Drawable drawable;
private Texture textureBtn;
public PlayState(GameStateManager gsm) {
super(gsm);
gameStateManager = gsm;
me = this;
entityManager = new EntityManager();
player = new Player(this, 100, 100);
border = new Border();
background = new Texture("bggame.png");
filter = new Texture("filter.png");
cam.setToOrtho(false, MinniMafia.WIDTH, MinniMafia.HEIGHT);
click = Gdx.audio.newSound(Gdx.files.internal("Click.mp3"));
boost = Gdx.audio.newSound(Gdx.files.internal("boost.mp3"));
drug = new Drug();
house = new House();
collectedDrugs = 0;
font = new BitmapFont();
entityManager.addEntity(player);
entityManager.addEntity(drug);
entityManager.addEntity(border);
entityManager.addEntity(house);
pause = false;
renderLost = false;
boostSound = false;
stage = new Stage();
textureBtn = new Texture("pausebtn.png");
drawable = new TextureRegionDrawable(new TextureRegion(textureBtn));
button = new ImageButton(drawable);
button.setPosition(cam.position.x + cam.viewportWidth/2 - 50, cam.position.y + cam.viewportHeight/2 - 50);
button.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
gameStateManager.set(new PauseState(gameStateManager, me));
}
});
stage.addActor(button);
Gdx.input.setInputProcessor(button.getStage());
}
#Override
protected void handleInput() {
if (Gdx.input.justTouched()) {
click.play(0.2f);
}
if (Gdx.input.isTouched()) {
player.setStop(true);
boostSound = false;
} else {
if (!boostSound) {
boost.play(0.2f);
boostSound = true;
}
player.setStop(false);
}
}
#Override
public void update(float dt) {
Gdx.input.setInputProcessor(stage);
if(Gdx.input.getInputProcessor() == stage){
System.out.println("All working");
}else{
System.out.println("Error");
}
if (!pause) {
handleInput();
entityManager.updateEntities(dt);
setCam();
button.setPosition(cam.position.x + cam.viewportWidth/2 - 60, cam.position.y + cam.viewportHeight/2 - 60);
if (drug.collides(player.getBounds())) {
entityManager.disposeEntity(drug);
player.setGotDrug(true);
}
if (border.collides(player.getBounds()) && !border.isOpen()) {
pause = true;
renderLost = true;
}
if (house.collides(player.getBounds()) && player.isGotDrug()) {
player.setGotDrug(false);
collectedDrugs++;
drug = new Drug();
entityManager.addEntity(drug);
}
} else if (renderLost = true) {
if (Gdx.input.isTouched()) {
gsm.set(new MenuState(gsm));
dispose();
}
}
}
#Override
public void render(SpriteBatch sb) {
sb.setProjectionMatrix(cam.combined);
sb.begin();
sb.draw(background, 0, 0);
entityManager.renderEntities(sb);
button.draw(sb, 10f);
font.draw(sb, "" + collectedDrugs, cam.position.x - cam.viewportWidth / 2 + 10, cam.position.y - cam.viewportHeight / 2 + 20);
if (renderLost) {
sb.draw(filter, cam.position.x - cam.viewportWidth / 2, cam.position.y - cam.viewportHeight / 2);
font.draw(sb, "LOST! SCORE:" + collectedDrugs, cam.position.x - 50, cam.position.y);
}
sb.end();
}
#Override
public void dispose() {
background.dispose();
entityManager.disposeAll();
click.dispose();
}
private void setCam() {
float camViewportHalfX = cam.viewportWidth * .5f;
float camViewportHalfY = cam.viewportHeight * .5f;
cam.position.x = player.getPosition().x;
cam.position.y = player.getPosition().y;
cam.position.x = MathUtils.clamp(cam.position.x, camViewportHalfX, FIELD_SIZE_WIDTH - camViewportHalfX);
cam.position.y = MathUtils.clamp(cam.position.y, camViewportHalfY, FIELD_SIZE_HEIGHT - camViewportHalfY);
cam.update();
}
public Drug getDrug() {
return drug;
}
public House getHouse() {
return house;
}
}
I really don't know where the problem is. Could you help me please?

Temporary Sprite in Android App

I have an android game where there are sprites moving about the screen. When one is hit, it adds or takes away from the score and then disappears.
What I would like it to do is create a blood splatter when it is hit which will also disappear.
I have actually achieved this but the blood splatter doesn't appear where the sprite was hit. It always goes to the bottom right-hand corner. I was wondering if there is anyone out there that can see where my problem is.
I have a TempSprite class just for the blood splatter and this is below:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
All the other code is in the GameView class, specifically in the doDraw and GameView methods:
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private final Bitmap bmpBlood;
/* Member (state) fields */
private GameLoopThread gameLoopThread;
private Paint paint; //Reference a paint object
/** The drawable to use as the background of the animation canvas */
private Bitmap mBackgroundImage;
// For creating the game Sprite
private Sprite sprite;
private BadSprite badSprite;
// For recording the number of hits
private int hitCount;
// For displaying the highest score
private int highScore;
// To track if a game is over
private boolean gameOver;
// To play sound
private SoundPool mySound;
private int zapSoundId;
private int screamSoundId;
// For multiple sprites
private ArrayList<Sprite> spritesArrayList;
private ArrayList<BadSprite> badSpriteArrayList;
// For the temp blood image
private List<TempSprite> temps = new ArrayList<TempSprite>();
//int backButtonCount = 0;
private void createSprites() {
// Initialise sprite object
spritesArrayList = new ArrayList<>();
badSpriteArrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
spritesArrayList.add(new Sprite(this));
badSpriteArrayList.add(new BadSprite(this));
}
}
public GameView(Context context) {
super(context);
// Focus must be on GameView so that events can be handled.
this.setFocusable(true);
// For intercepting events on the surface.
this.getHolder().addCallback(this);
// Background image added
mBackgroundImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.castle);
// Populate multiple sprites
//createSprites();
//Vibrator vibe = (Vibrator) sprite.getSystemService(Context.VIBRATOR_SERVICE);
//vibe.vibrate(500);
// For the temp blood splatter
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
//Sound effects for the sprite touch
mySound = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
screamSoundId = mySound.load(context, R.raw.scream, 1);
zapSoundId = mySound.load(context, R.raw.zap, 1);
}
/* Called immediately after the surface created */
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
// We can now safely setup the game start the game loop.
ResetGame();//Set up a new game up - could be called by a 'play again option'
mBackgroundImage = Bitmap.createScaledBitmap(mBackgroundImage, getWidth(), getHeight(), true);
gameLoopThread = new GameLoopThread(this.getHolder(), this);
gameLoopThread.running = true;
gameLoopThread.start();
}
// For the countdown timer
private long startTime; // Timer to count down from
private final long interval = 1 * 1000; // 1 sec interval
private CountDownTimer countDownTimer; // Reference to the class
private boolean timerRunning = false;
private String displayTime; // To display the time on the screen
//To initialise/reset game
private void ResetGame(){
/* Set paint details */
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
sprite = new Sprite(this);
hitCount = 0;
// Set timer
startTime = 10; // Start at 10s to count down
// Create new object - convert startTime to milliseconds
countDownTimer = new MyCountDownTimer(startTime*1000, interval);
countDownTimer.start(); // Start the time running
timerRunning = true;
gameOver = false;
}
// Countdown Timer - private class
private class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer (long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
//displayTime = "Time is up!";
timerRunning = false;
countDownTimer.cancel();
gameOver = true;
}
public void onTick (long millisUntilFinished) {
displayTime = " " + millisUntilFinished / 1000;
}
}
//This class updates and manages the assets prior to drawing - called from the Thread
public void update(){
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
#SuppressWarnings("ResourceAsColor")
public void doDraw(Canvas canvas) {
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
if (!gameOver) {
sprite.draw(canvas);
//paint.setColor(R.color.red);
canvas.drawText("Time Remaining: " + displayTime, 35, 50, paint);
canvas.drawText("Number of hits: " + hitCount, 35, 85, paint);
// Draw the blood splatter
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
// Draw all the objects on the canvas
for (int i = 0; i < spritesArrayList.size(); i++) {
Sprite sprite = spritesArrayList.get(i);
sprite.draw(canvas);
}
for (int i = 0; i < badSpriteArrayList.size(); i++) {
BadSprite badSprite = badSpriteArrayList.get(i);
badSprite.draw(canvas);
}
} else {
canvas.drawText("Game Over!", 35, 50, paint);
canvas.drawText("Your score was: " + hitCount, 35, 80, paint);
canvas.drawText("To go back home,", 280, 50, paint);
canvas.drawText("press the 'back' key", 280, 70, paint);
}
}
//To be used if we need to find where screen was touched
public boolean onTouchEvent(MotionEvent event) {
for (int i = spritesArrayList.size()-1; i>=0; i--) {
Sprite sprite = spritesArrayList.get(i);
if (sprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(zapSoundId, 1.0f, 1.0f, 0,0, 1.5f);
spritesArrayList.remove(sprite);
//temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount--;
return super.onTouchEvent(event);
}
for (int i1 = badSpriteArrayList.size()-1; i1>=0; i1--) {
BadSprite badSprite = badSpriteArrayList.get(i1);
if (badSprite.wasItTouched(event.getX(), event.getY())) {
mySound.play(screamSoundId, 1.0f, 1.0f, 0, 0, 1.5f);
badSpriteArrayList.remove(badSprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
hitCount++;
return super.onTouchEvent(event);
}
}
}
//else {
return true;
// }
}
public void surfaceDestroyed(SurfaceHolder holder) {
gameLoopThread.running = false;
// Shut down the game loop thread cleanly.
boolean retry = true;
while(retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public int getHitCount() {
return hitCount;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
As always, any help greatly appreciated.
Thanks
This was solved with the following code:
public class TempSprite {
private float x;
private float y;
private Bitmap bmp;
private int life = 12;
private List<TempSprite> temps;
public TempSprite(List<TempSprite> temps, GameView gameView, float x,
float y, Bitmap bmp) {
/*this.x = Math.min(Math.max(x - bmp.getWidth() / 2, 0),
gameView.getWidth() - bmp.getWidth());
this.y = Math.min(Math.max(y - bmp.getHeight() / 2, 0),
gameView.getHeight() - bmp.getHeight());*/
this.x = x;
this.y = y;
this.bmp = bmp;
this.temps = temps;
}
public void onDraw(Canvas canvas) {
update();
canvas.drawBitmap(bmp, x, y, null);
}
private void update() {
if (--life < 1) {
temps.remove(this);
}
}
}
You can see where the commented out sections are and below are what they were replaced with. I was trying to make things a little too complicated.

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.

FitViewPort Android libGDX

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;
}
}
}

Categories

Resources