libGDX consult with speed - java

What i need to do is, when the points its "example 10" the speed of the ball raise, when the points its "example 20" the speed of the ball raises again, etc. I dont know if i do that in the Ball class or in the GameScreen class and i dont know how to do it. Thanks for your help!.
public class Ball {
//THE SPEED OF THE BALL
private static final float SPEED=1100;
//THE POINTS IS
puntuacion =0;
//AND THE METHOD WHEN THE POINTS IS INCREAMENTING
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();
}
}
EDIT:
This is my GameScreen class.
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 (puntuacion % 10 == 0){
SPEED = 200;
}
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;
}
}
}

I need 50 reputation to comment so instead I'll post an answer and try to make it as helpful as possible.
First of all I'm not too sure of your question, but from what I understand, you want to increase the speed of your ball when puntuacion reaches certain values (10, 20, etc).
The first thing you have to do is remove the final from your SPEED variable, since a final primitive can only be set once, thus denying you from changing it later on.
As for updating the speed, if you want to do it at specific values of punctuacion, then simply do
if(punctuacion == 10 || punctuacion == 17) { // etc
speed += x; // x being the value you want to increase the speed by
}
Alternatively, if you want to update the speed every 10 increments for example, you could do
if (punctuacion % 10 == 0){
speed += x;
}
Do note that for this second example, when punctuacion is 0, the if statement will return true, so work around that if you have to.
As for where to put this code, it really depends on your classes and you definitely didn't post enough code for me to be able to help you with that, but my best guess would be to put it right after you increment punctuacion, since I'm assuming you want the ball's speed update check to be performed immediately after punctuacion updates.

This is my GameScreen class.
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 (puntuacion % 10 == 0){
SPEED = 200;
}
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

Adding a main class to my game so I can make a jar file

I made a game in java to practice mouse accuracy on JGrasp with the little knowledge I have with programming. Now I'm trying to create a jar file for it. However, I don't have a main class and I just run it within JGrasp at the moment. I've been trying to figure out how to run it with a main class but all the things I tried didn't work. My understanding is really low. I have no idea what to do. I don't know how to make it so my code can be accessed by a main method.
import java.awt.event.*;
import java.awt.*;
import java.util.Random;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Timer;
public class Aim extends java.applet.Applet implements Runnable, MouseListener, ComponentListener {
// position of center circle (coordinates)
private int scale = 500; // decide size of game
private int seed;
private int turn;
private Dimension size;
private Image image;
private Image background;
private Image gameOverImg;
private Image timerImgOnes;
private Image timerImgTens;
private Image timerImgMins;
private Image timerImgColon;
private Image scorePerMinImg;
private Image speedUpImg;
private Image lifeImg;
private Image yourTime;
private Graphics g;
private double targetScale = 6; // scale of targets (higher number = smaller targets)
private double originalTargetScale = targetScale;
private int circleScale = (int) (scale / targetScale);
private int circleScale2 = (int) (scale / (targetScale*1.35));
private int originalCircleScale = circleScale;
private int originalCircleScale2 = circleScale2;
private int eraseScale = (int) (scale / (targetScale-(targetScale*.1)));
private int eraseOffset = circleScale / 2;
private int mx = (scale/2) - (circleScale2/2);
private int my = mx;
private int mxO = mx;
private int myO = mx;
private double distScale = 1.3; // scale of how close the targets will be to each other
private int flick = 1;
private int flick2 = 1;
long tStart = System.currentTimeMillis();
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;
private int gameOver;
private int newGame;
private int life = 3; // amount of lives
// used to determine users score per minute
private double score = 1;
private double scorePerMin;
private double requiredScorePerMin;
private int difficulty = 30; // Choose difficulty of speed. Lower # is harder
private int distance1 = (int) Math.hypot(circleScale*distScale, circleScale*distScale);
private int distance2 = (int) (circleScale * distScale);
// array for possible spots for the outer circle to spawn
private int[] mx2 = { mx + distance1, mx + distance2, mx + distance2, mx, mx, mx-distance1, mx-distance2, mx-distance2, };
private int[] my2 = { my, my-distance2, my+distance2, my-distance1, my+distance1, my, my-distance2, my+distance2, };
Random random = new Random();
Thread runner;
Timer T = new Timer();
// variables & array to paint timer & speed bar
private String[] timerImgArray = { "res/zero.png", "res/one.png", "res/two.png", "res/three.png", "res/four.png", "res/five.png", "res/six.png", "res/seven.png", "res/eight.png", "res/nine.png" };
private int ones;
private int tens;
private int mins;
private int timerDisplayScale;
private int timerCenter;
private int temp;
private int elapsedSecondsShort;
private int c;
private int timerDisplacement;
private int scoreBarSize;
private String[] lifeImgArray = { "res/life0.png", "res/life1.png", "res/life2.png", "res/life3.png" };
public void start() {
if (runner == null) {
runner = new Thread(this);
long tStart = System.currentTimeMillis();
runner.start();
}
}
public void run() {
while (true) {
if (life > 0) {
// Timer used for gametime display & score per minute calculation
tEnd = System.currentTimeMillis();
tDelta = tEnd - tStart;
elapsedSeconds = tDelta / 1000.0;
temp = (int)(elapsedSeconds*1);
elapsedSecondsShort = ((int)temp)/1;
c++;
if (requiredScorePerMin > scorePerMin) {
life = 0;
gameOver=1;
}
// calculate score per minute & required score per minute
scorePerMin = 60 * (score / elapsedSeconds);
requiredScorePerMin = 60 * (1 + (elapsedSeconds / difficulty));
// update all variables each frame
circleScale = (int) (scale / targetScale);
circleScale2 = (int) (scale / (targetScale*1.35));
eraseScale = (int) (scale / (targetScale-(targetScale*.1)));
eraseOffset = circleScale / 2;
mx = (scale/2) - (circleScale2/2);
my = mx;
distance1 = (int) Math.hypot(circleScale*distScale, circleScale*distScale);
distance2 = (int) (circleScale * distScale);
int zoomSize1 = (int)(scale/(originalCircleScale2/2.5));
int zoomSize2 = (int)(scale/(originalCircleScale/2.5));
// Calculates how much each circle will change in size throughout each zoom
if (Math.abs(circleScale - originalCircleScale) >= zoomSize1) flick*=-1;
if (Math.abs(circleScale2 - originalCircleScale2) >= zoomSize2) flick2*=-1;
// increases & decreases the size of targets
if (turn == 1){
if (flick2==-1) targetScale+= .05;
else targetScale-= .05;
}
if (turn == 0){
if (flick==-1) targetScale+= .05;
else targetScale-= .05;
}
// updates coordinates of outer circle
if (turn==1){
switch (seed) {
case 0:
mx2[seed] = mxO + distance1;
my2[seed] = myO;
break;
case 1:
mx2[seed] = mxO + distance2;
my2[seed] = myO - distance2;
break;
case 2:
mx2[seed] = mxO + distance2;
my2[seed] = myO + distance2;
break;
case 3:
mx2[seed] = mxO;
my2[seed] = myO - distance1;
break;
case 4:
mx2[seed] = mxO;
my2[seed] = myO + distance1;
break;
case 5:
mx2[seed] = mxO - distance1;
my2[seed] = myO;
break;
case 6:
mx2[seed] = mxO - distance1;
my2[seed] = myO - distance2;
break;
case 7:
mx2[seed] = mxO - distance2;
my2[seed] = myO - distance2;
break;
case 8:
mx2[seed] = mxO - distance2;
my2[seed] = my + distance2;
break;
}
}
// Finish updating variables
repaint();
if (life == 0) {
stop();
}
try { Thread.sleep(7); }
catch (InterruptedException e) {}
}
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void init() {
setSize(scale, scale);
size = getSize();
addMouseListener(this);
background = getImage(getDocumentBase(), "res/background.jpg");
gameOverImg = getImage(getDocumentBase(), "res/gameOver.jpg");
image = getImage(getDocumentBase(), "res/aim.png");
scorePerMinImg = getImage(getDocumentBase(), "res/SPM.png");
speedUpImg = getImage(getDocumentBase(), "res/speedUp.png");
}
public void update(Graphics g) {
Dimension newSize = getSize();
if (size.equals(newSize)) {
paint(g);
}
}
// paint center circle
public void paint(Graphics g) {
if (gameOver != 1){
if (turn == 0){
flick2 = -1;
scoreBarSize = (int) (scorePerMin - requiredScorePerMin);
g.setColor(Color.black);
g.drawImage(background, 0, 0, scale, scale, this);
timerDisplay();
g.drawImage(timerImgOnes, timerCenter + (timerDisplayScale / 2), 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(timerImgTens, timerCenter + (timerDisplayScale / 4), 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(timerImgMins, timerCenter - (timerDisplayScale/4), 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(timerImgColon, timerCenter, 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(scorePerMinImg, (scale/2) - scoreBarSize/2, scale - (scale/20), scoreBarSize, originalCircleScale2 / 4, this);
if (scoreBarSize < 35) g.drawImage(speedUpImg, (scale/2) - (originalCircleScale2/2), scale - (scale/11), scale/8, scale/20, this);
lifeImg = getImage(getDocumentBase(), lifeImgArray[life]);
g.drawImage(lifeImg, scale - (scale/14), (scale/2) - (originalCircleScale2/2), scale / 15, scale / 6, this);
g.drawImage(image, mx, my , circleScale2, circleScale2, this);
} else { // paint outer, moving circle
flick = -1;
scoreBarSize = (int) (scorePerMin - requiredScorePerMin);
g.drawImage(background, 0, 0, scale, scale, this);
g.drawImage(image, mx2[seed], my2[seed], circleScale, circleScale, this);
timerDisplay();
g.drawImage(timerImgOnes, timerCenter + (timerDisplayScale / 2), 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(timerImgTens, timerCenter + (timerDisplayScale / 4), 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(timerImgMins, timerCenter - (timerDisplayScale/4), 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(timerImgColon, timerCenter, 25 , originalCircleScale2 / 2, originalCircleScale2 / 2, this);
g.drawImage(scorePerMinImg, (scale/2) - scoreBarSize/2, scale - (scale/20), scoreBarSize, originalCircleScale2 / 4, this);
if (scoreBarSize < 35) g.drawImage(speedUpImg, (scale/2) - (originalCircleScale2/2), scale - (scale/11), scale/8, scale/20, this);
lifeImg = getImage(getDocumentBase(), lifeImgArray[life]);
g.drawImage(lifeImg, scale - (scale/14), (scale/2) - (originalCircleScale2/2), scale / 15, scale / 6, this);
}
} else{
g.drawImage(gameOverImg, 0, 0, scale, scale, this);
g.drawImage(timerImgOnes, scale - scale/3 + (timerDisplayScale / 2) - timerDisplayScale/3, scale - scale/7 , (originalCircleScale2/3)*2, (originalCircleScale2/3)*2, this);
g.drawImage(timerImgTens, scale - scale/3 + (timerDisplayScale / 4) - timerDisplayScale/3, scale - scale/7 , (originalCircleScale2/3)*2, (originalCircleScale2/3)*2, this);
g.drawImage(timerImgMins, scale - scale/3 - (timerDisplayScale / 4) - timerDisplayScale/3, scale - scale/7 , (originalCircleScale2/3)*2, (originalCircleScale2/3)*2, this);
g.drawImage(timerImgColon, scale - scale/3 - timerDisplayScale/3, scale - scale/7 , (originalCircleScale2/3)*2, (originalCircleScale2/3)*2, this);
g.drawImage(yourTime, timerCenter - ((timerDisplayScale*2)), scale - (scale/6) , scale/2, scale / 9, this);
}
}
// updating the timer images
public void timerDisplay(){
if ((c == 128) && (ones != 9)) {
ones++;
c = 0;
}
if ((ones == 9) && ( c == 128)){
tens++;
ones = 0;
c = 0;
}
if ((tens == 5) && (ones == 9) && (c == 128)) {
mins++;
tens = 0;
ones = 0;
c = 0;
}
timerDisplacement = timerDisplayScale/4;
timerDisplayScale = scale / 5;
timerCenter = (scale / 2) - timerDisplacement;
timerImgOnes = getImage(getDocumentBase(), timerImgArray[ones]);
timerImgTens = getImage(getDocumentBase(), timerImgArray[tens]);
timerImgMins = getImage(getDocumentBase(), timerImgArray[mins]);
timerImgColon = getImage(getDocumentBase(), "res/colon.png");
yourTime = getImage(getDocumentBase(), "res/yourTime.png");
}
/*
* Mouse methods
*/
public void mousePressed(MouseEvent e) {
if (turn == 0) seed = random.nextInt(8);
if (turn == 1) turn = 0; else turn = 1;
targetScale = originalTargetScale; // reset size of circle each time it is spawned
if (Math.abs(circleScale - originalCircleScale) >= 20) flick*=-1;
if (Math.abs(circleScale2 - originalCircleScale2) >= 20) flick2*=-1;
int x = e.getX();
int y = e.getY();
e.consume();
requestFocus();
int xDif = x - mx - (circleScale2 / 2);
int yDif = y - my - (circleScale2 / 2);
int xDif2 = x - mx2[seed] - (circleScale / 2);
int yDif2 = y - my2[seed] - (circleScale / 2);
if (gameOver != 1){
//determine if hit
if ((Math.hypot(xDif, yDif) <= (circleScale2 / 2) && turn == 1) || (Math.hypot(xDif2, yDif2) <= (circleScale / 2) && turn == 0)){
score++;
getAppletContext().showStatus("HIT");
play(getCodeBase(), "sounds/hit.au");
}
else { //miss
life--;
if (life == 0) {
gameOver=1;
}
getAppletContext().showStatus("MISSED");
play(getCodeBase(), "sounds/whoosh.au");
}
}
repaint();
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentResized(ComponentEvent e) {
repaint();
}
public void componentShown(ComponentEvent e) {
}
public void destroy() {
removeMouseListener(this);
}
public String getAppletInfo() {
return "Title: Mouse Accuracy";
}
}
The java main method is:
public static void main(String [ ] args){
//do stuff
}
Put your starting method in and it will run fine.
I would still recommend you the swing JFrame instead of the applet bc it is way more updated and handy in my opinion.

Save currentTime as long (AndroidStudio/libgdx

I am currently coding a game with Android Studio in the style of FlappyBird. I have two Cooldowns that give the user the possibility to use extra abilities.
In the main game view you can see 2 images that are grey and a timer under them. The timer goes from 10 to 0 and when zero is reached the number disappears, the image gets colored and the user knows he is able to activate the ability in the pause screen.
The problem:
When the game is starting the timer starts also and goes down as i wanted. But if the user enters the Pause Menu the Timer should stop and if he leaves it the Timer should run again.
I have a
long startTime = 0;
and a
long elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
It all works but I cannot save the current time in a long and can't find any function for it!
I know the code is very long but the important part is in the drawWorld()-method in the if statement GameState.Running.
public class PlaneGame extends ApplicationAdapter{
private static final float PLANE_JUMP_IMPULSE = 350;
private static final float GRAVITY = -20;
private static final float PLANE_VELOCITY_X = 200;
private static final float PLANE_START_Y = 240;
private static final float PLANE_START_X = 50;
private static final int STATE_START = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_OVER = 2;
SpriteBatch batch;
OrthographicCamera camera;
OrthographicCamera uiCamera;
Texture background;
TextureRegion ground;
float groundOffsetX = 0;
TextureRegion ceiling;
TextureRegion rock;
TextureRegion rockDown;
TextureRegion planeSmall;
TextureRegion planeSmallBlack;
Animation plane;
TextureRegion ready;
TextureRegion gameOver;
TextureRegion pause;
BitmapFont font;
Vector2 planePosition = new Vector2();
Vector2 planeVelocity = new Vector2();
float planeStateTime = 0;
Vector2 gravity = new Vector2();
Array<Rock> rocks = new Array<Rock>();
GameState gameState = GameState.Start; /*neeeeeeewwwww*/
int score = 0;
long startTime = 0;
long startTime2;
long elapsedTime;
long savedTime;
boolean wantToSeeTime = true;
boolean wantToSeeTimePause = true;
float timeCdRock = 0;
float timeCdPlane = 0;
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle();
Music music;
Sound point;
Sound explode;
//this gets called repeatedly to run the game
#Override
public void render () {
//clear the screen so we can draw the next one
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
long saveTime = elapsedTime;
//update the position of the plane and rocks
updateWorld();
elapsedTime = saveTime;
//now draw the updated screen
drawWorld();
}
//initialize objects and load assets when game starts
#Override
public void create () {
startTime = TimeUtils.nanoTime(); /*Neeeewwwwwwwww !!!*/
Gdx.input.setInputProcessor(new GestureDetector(new MyGestureListener()));
batch = new SpriteBatch();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
uiCamera = new OrthographicCamera();
uiCamera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
uiCamera.update();
font = new BitmapFont(Gdx.files.internal("arial.fnt"));
background = new Texture("background.png");
ground = new TextureRegion(new Texture("ground.png"));
ceiling = new TextureRegion(ground);
ceiling.flip(true, true);
rock = new TextureRegion(new Texture("rock.png"));
rockDown = new TextureRegion(rock);
rockDown.flip(false, true);
Texture frame1 = new Texture("plane1.png");
frame1.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Texture frame2 = new Texture("plane2.png");
Texture frame3 = new Texture("plane3.png");
planeSmall = new TextureRegion(new Texture("planeSmall.png"));
planeSmallBlack = new TextureRegion(new Texture("planeSmallBlack.png"));
ready = new TextureRegion(new Texture("ready.png"));
gameOver = new TextureRegion(new Texture("gameover.png"));
pause = new TextureRegion(new Texture("pause.png"));
plane = new Animation(0.05f, new TextureRegion(frame1), new TextureRegion(frame2), new TextureRegion(frame3), new TextureRegion(frame2));
plane.setPlayMode(PlayMode.LOOP);
music = Gdx.audio.newMusic(Gdx.files.internal("music.mp3"));
music.setLooping(true);
music.play();
point = Gdx.audio.newSound(Gdx.files.internal("point.ogg"));
explode = Gdx.audio.newSound(Gdx.files.internal("explode.wav"));
resetWorld();
}
//reset the state of the game
private void resetWorld() {
score = 0;
startTime = 0;
groundOffsetX = 0;
planePosition.set(PLANE_START_X, PLANE_START_Y);
planeVelocity.set(0, 0);
gravity.set(0, GRAVITY);
camera.position.x = 400;
//randomize the position and direction of the rocks
rocks.clear();
for(int i = 0; i < 5; i++) {
boolean isDown = MathUtils.randomBoolean();
rocks.add(new Rock(700 + i * 200, isDown?480-rock.getRegionHeight(): 0, isDown? rockDown: rock));
}
}
//use the time elapsed since the last call to render() to determine how much to update the game
private void updateWorld() {
float deltaTime = Gdx.graphics.getDeltaTime();
planeStateTime += deltaTime;
/*if(Gdx.input.justTouched()) {
if(gameState == STATE_START) {
gameState = STATE_RUNNING;
}
if(gameState == STATE_RUNNING) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == STATE_OVER) {
gameState = STATE_START;
resetWorld();
}
}*/
if(gameState != GameState.Start) planeVelocity.add(gravity);
planePosition.mulAdd(planeVelocity, deltaTime);
camera.position.x = planePosition.x + 350;
if(camera.position.x - groundOffsetX > ground.getRegionWidth() + 400) {
groundOffsetX += ground.getRegionWidth();
}
rect1.set(planePosition.x + 20, planePosition.y, plane.getKeyFrames()[0].getRegionWidth() - 20, plane.getKeyFrames()[0].getRegionHeight());
for(Rock r: rocks) {
//if the rock is off the screen, give it a new location in front of the plane
if(camera.position.x - r.position.x > 400 + r.image.getRegionWidth()) {
boolean isDown = MathUtils.randomBoolean();
r.position.x += 5 * 200;
r.position.y = isDown?480-rock.getRegionHeight(): 0;
r.image = isDown? rockDown: rock;
r.counted = false;
}
rect2.set(r.position.x + (r.image.getRegionWidth() - 30) / 2 + 20, r.position.y, 20, r.image.getRegionHeight() - 10);
//check if the plane crashed
if(rect1.overlaps(rect2)) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
//award a point for not crashing into a rock
if(r.position.x < planePosition.x && !r.counted) {
score++;
r.counted = true;
point.play();
}
}
//check if the plane crashed
if(planePosition.y < ground.getRegionHeight() - 20 ||
planePosition.y + plane.getKeyFrames()[0].getRegionHeight() > 480 - ground.getRegionHeight() + 20) {
if(gameState != GameState.GameOver) explode.play();
gameState = GameState.GameOver;
planeVelocity.x = 0;
}
}
//draw the background, rocks, and plane to the screen and possibly some ui text
private void drawWorld() {
elapsedTime = (System.currentTimeMillis() - startTime) / 1000;
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(background, camera.position.x - background.getWidth() / 2, 0);
for(Rock rock: rocks) {
batch.draw(rock.image, rock.position.x, rock.position.y);
}
batch.draw(ground, groundOffsetX, 0);
batch.draw(ground, groundOffsetX + ground.getRegionWidth(), 0);
batch.draw(ceiling, groundOffsetX, 480 - ceiling.getRegionHeight());
batch.draw(ceiling, groundOffsetX + ceiling.getRegionWidth(), 480 - ceiling.getRegionHeight());
batch.draw(plane.getKeyFrame(planeStateTime), planePosition.x, planePosition.y);
batch.end();
batch.setProjectionMatrix(uiCamera.combined);
batch.begin();
if(gameState == GameState.Start) {
batch.draw(ready, Gdx.graphics.getWidth() / 2 - ready.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - ready.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver) {
batch.draw(gameOver, Gdx.graphics.getWidth() / 2 - gameOver.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - gameOver.getRegionHeight() / 2);
}
if(gameState == GameState.GameOver || gameState == GameState.Running) {
font.draw(batch, "" + score, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() - 60);
}
if(gameState == GameState.Running || gameState == GameState.Pause) {
//font.draw(batch, "" + (10 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
if(wantToSeeTime){
font.draw(batch, "" + (5 - elapsedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
if((5 -(elapsedTime) > 0)) {
batch.draw(planeSmallBlack, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
}else {
batch.draw(planeSmall, (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 250);
wantToSeeTime = false;
}
}
if(gameState == GameState.Pause){
batch.draw(pause, Gdx.graphics.getWidth() / 2 - pause.getRegionWidth() / 2, Gdx.graphics.getHeight() / 2 - pause.getRegionHeight() / 2);
if(wantToSeeTimePause){
font.draw(batch, "" + (savedTime), (Gdx.graphics.getWidth() / 2) / 3, Gdx.graphics.getHeight() - 260);
}
}
batch.end();
}
//object to hold all pertinent information for a rock
static class Rock {
Vector2 position = new Vector2();
TextureRegion image;
boolean counted;
public Rock(float x, float y, TextureRegion image) {
this.position.x = x;
this.position.y = y;
this.image = image;
}
}
// Neeeeeeeewwwww
static enum GameState {
Start, Running, GameOver, Pause
}
private class MyGestureListener implements GestureDetector.GestureListener {
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean tap(float x, float y, int count, int button) {
if(gameState == GameState.Start) {
gameState = GameState.Running;
startTime = System.currentTimeMillis();
}
if(gameState == GameState.Running) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
}
if(gameState == GameState.GameOver) {
gameState = GameState.Start;
resetWorld();
}
/*if((gameState == GameState.Pause) && (count == 2)) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean longPress(float x, float y) {
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
if(gameState == GameState.Running) {
planePosition.set(planePosition.x, planePosition.y);
planeVelocity.set(0,0);
gravity.set(0, 0);
savedTime = System.currentTimeMillis() / 1000;
wantToSeeTime = false;
wantToSeeTimePause = true;
gameState = GameState.Pause;
} else {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
wantToSeeTime = true;
wantToSeeTimePause = false;
elapsedTime -= savedTime;
gameState = GameState.Running;
}
/*if(gameState == GameState.Pause) {
planeVelocity.set(PLANE_VELOCITY_X, PLANE_JUMP_IMPULSE);
gravity.set(0,GRAVITY);
gameState = GameState.Running;
}*/
return true;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
return false;
}
public void pinchStop() {
}
}
}
Thanks for your help!
You can use joda time for advanced operations
Please check the link for your reference
http://www.joda.org/joda-time/userguide.html
I'm going to assume that your game runs as part of a loop. Ideally what you should have is a starting time when the ability is activated, which counts down during the cooldown based on how much time has elapsed since the last iteration of your loop. For example, for an ability with a 10 second cooldown:
final long abilityLength = 10 * 1000;
long cooldownRemaining = 0;
long lastTimestamp;
boolean isPaused = false;
private void doAbility() {
if (cooldownRemaining <= 0) {
cooldownRemaining = abilityLength;
}
}
public void main(int[] args) {
lastTimestamp = System.currentTimeMillis();
while(true) { // your main game loop
// Time (in ms) elapsed since the last iteration of this loop
long delta = System.currentTimeMillis() - lastTimestamp;
... // Other game code
if (cooldownRemaining > 0 && !isPaused) {
// Subtract the delta from the remaing cooldown time.
cooldownRemaining -= delta;
}
lastTimeStamp = System.currentTimeMillis();
}
}

Pixel collision detection in libgdx

I am creating a maze game in libGDX. The background texture is very similar to this one: http://www.wpclipart.com/recreation/games/maze/maze_square_medium.png
My moving character is on the maze, and I would like to do collision detection between the character and black walls by checking the colour of my maze texture, without creating rectangles and figuring out all the coordinates of the maze walls, if that is possible. I have researched a lot, but since I am quite new to libGDX and even java, I haven't really found anything that made a lot of sense to me for my case. If anyone has an answer for me on how I could do this or can refer me to a page that explains this well, it would be very greatly appreciated!
EDIT:
This is my code right now:
private static final int COLS = 4;
private static final int ROWS = 4;
Sprite sprChar, sprMaze;
SpriteBatch batch;
Texture Sprite;
TextureRegion[] frames;
TextureRegion CurrentFrame;
float fTime = 0f, fSpeed = 4;
Animation animation;
Texture txtMaze;
Pixmap pixmap;
int nX, nY, nPix, nR, nG, nB, nA;
Color color;
#Override
public void create() {
batch = new SpriteBatch();
Sprite = new Texture(Gdx.files.internal("snowwhite.png"));
sprChar = new Sprite(Sprite);
sprChar.setPosition(300, 200);
TextureRegion[][] tmp = TextureRegion.split(Sprite, Sprite.getWidth() / COLS, Sprite.getHeight(
frames = new TextureRegion[COLS * ROWS];
int index = 0;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
frames[index++] = tmp[i][j];
}
}
animation = new Animation(1f, frames);
sprChar.setPosition(10, 10);
pixmap = new Pixmap(Gdx.files.internal("Maze2.png"));
color = new Color();
}
#Override
public void render() {
if (fTime < 4) {
fTime += Gdx.graphics.getDeltaTime();
} else {
fTime = 0;
}
nX = Math.round(sprChar.getX());
nY = Math.round(sprChar.getY());
nPix = pixmap.getPixel(nX, nY);
Color.rgba8888ToColor(color, nPix);
nR = (int) (color.r * 255f);
nG = (int) (color.g * 255f);
nB = (int) (color.b * 255f);
nA = (int) (color.a * 255f);
if (nR == 0 && nG == 0 && nB == 0) {
System.out.println("is hit");
}
txtMaze = new Texture(pixmap);
sprMaze = new Sprite(txtMaze);
CurrentFrame = animation.getKeyFrame(0);
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
sprChar.setX(sprChar.getX() - fSpeed);
CurrentFrame = animation.getKeyFrame(4 + fTime);
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
sprChar.setX(sprChar.getX() + fSpeed);
CurrentFrame = animation.getKeyFrame(8 + fTime);
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
sprChar.setY(sprChar.getY() + fSpeed);
CurrentFrame = animation.getKeyFrame(12 + fTime);
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
sprChar.setY(sprChar.getY() - fSpeed);
CurrentFrame = animation.getKeyFrame(0 + fTime);
}
batch.begin();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.draw(sprMaze, sprMaze.getX(), sprMaze.getY(), sprMaze.getWidth() / 2,
sprMaze.getHeight() / 2, sprMaze.getWidth(),
sprMaze.getHeight(), sprMaze.getScaleX(),
sprMaze.getScaleY(), sprMaze.getRotation());
batch.draw(CurrentFrame, sprChar.getX(), sprChar.getY(), 20, 20);
batch.end();
}
public static void updatePosition(Sprite spr, float fX, float fY) {
spr.setPosition(fX, fY);
}
I just want it to output "is hit" if it passes a black wall, but I don't believe I am getting correct responses. Also, if I try to resize the maze sprite, it seems to me that it still checks for pixels on the maze at the original size.
P.S. Please excuse my bad code, I am VERY new. So any help would be very greatly appreciated, as I am on a time crunch!! Thank you

Can't hide image on collision in libgdx?

I just started working with LibGDX and can't figure out how to hide an image when it collides with an object. In my game some dots come from the top of the screen and meet the dot at the bottom. When they meet the dots should hide that isn't happening.
This is the main Game Class
public class GameScreen implements Screen,InputProcessor {
final AmazingDot game;
//setting the height and width variables
private int height;
private int width;
private static int touchCounter;
//setting the two dots variables
private Texture playerDotImage;
private Texture gameDotImage;
private Texture gameDotImage1;
private Rectangle playerDotRectangle;
private Map<Rectangle,Texture> gameDotMap;
//storing the time of last dot in nano seconds
private long lastDotTime;
public GameScreen(final AmazingDot gam){
this.game = gam;
Gdx.input.setInputProcessor(this);
//getting the height and width of the user's screen
height = Gdx.graphics.getHeight();
width = Gdx.graphics.getWidth();
touchCounter =0;
//loading the images in the variables
playerDotImage = new Texture(Gdx.files.internal("images/dot2.png"));
gameDotImage = new Texture(Gdx.files.internal("images/dot1.png"));
gameDotImage1 = new Texture(Gdx.files.internal("images/dot2.png"));
//placing the player dot in the middle of the screen
playerDotRectangle = new Rectangle();
playerDotRectangle.x = width/ 2 - 64 / 2;
playerDotRectangle.y = 20;
playerDotRectangle.width = 64;
playerDotRectangle.height = 64;
gameDotMap = new ConcurrentHashMap<Rectangle, Texture>();
populateDots();
}
private void populateDots(){
Rectangle dots = new Rectangle();
dots.x = randomLocation();
dots.y = height;
dots.width = 64;
dots.height = 64;
Random rand = new Random();
int n = rand.nextInt(2) + 1;
if(n==1){
gameDotMap.put(dots,gameDotImage1);
}
else{
gameDotMap.put(dots,gameDotImage);
}
lastDotTime = TimeUtils.nanoTime();
}
private int randomLocation(){
int[] locations = new int[3];
locations[0]=0;
locations[1]=width/2-64/2;
locations[2]=width-64;
Random generator = new Random();
int randomIndex = generator.nextInt(locations.length);
return locations[randomIndex];
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.batch.draw(playerDotImage,playerDotRectangle.x,playerDotRectangle.y,playerDotRectangle.width,playerDotRectangle.height);
for(Map.Entry<Rectangle,Texture> dots : gameDotMap.entrySet()){
game.batch.draw(dots.getValue(),dots.getKey().x,dots.getKey().y);
}
game.batch.end();
// check if we need to create a new dot
if(TimeUtils.nanoTime() - lastDotTime > 1000000000) populateDots();
for(Rectangle dot : gameDotMap.keySet()){
int gameSpeed = 400;
int xSpeed = calXSpeed(gameSpeed);
dot.y = dot.y - gameSpeed * Gdx.graphics.getDeltaTime();
if(dot.x <width/2-64/2){
dot.x = dot.x + xSpeed*Gdx.graphics.getDeltaTime();
}
else if(dot.x>width/2-64/2){
dot.x = dot.x - xSpeed*Gdx.graphics.getDeltaTime();
}
if(dot.y + 64 < 0) gameDotMap.remove(dot);
if(dot.overlaps(playerDotRectangle)) {
//this is where I am trying to remove the map object on collision
gameDotMap.remove(dot);
}
}
}
private int calXSpeed(int gameSpeed){
int seconds = height/gameSpeed;
int distance = width/2-64/2;
int speed = distance/seconds;
return speed;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
touchCounter++;
if(touchCounter % 2==0){
playerDotImage = new Texture(Gdx.files.internal("images/dot2.png"));
}
else{
playerDotImage = new Texture(Gdx.files.internal("images/dot1.png"));
}
return true;
}
#Override
public void dispose() {
playerDotImage.dispose();
gameDotImage.dispose();
gameDotImage1.dispose();
}
}
EDIT
As you can see in the above image when the moving dot reaches the stationary dot, it should disappear. But here in my code the dot just moves past the stationary dot. I am using rectangles(LibGdx) to detect whether the dots overlap each other or not.
Define you Map as an ArrayMap like so:
private ArrayMap<Rectangle, Texture> gameDotMap;
Then you can rewrite you render method like this:
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.batch.draw(playerDotImage, playerDotRectangle.x, playerDotRectangle.y, playerDotRectangle.width, playerDotRectangle.height);
for (int i = 0; i < gameDotMap.size; i++) {
game.batch.draw(gameDotMap.getValueAt(i), gameDotMap.getKeyAt(i).x, gameDotMap.getKeyAt(i).y);
}
game.batch.end();
// check if we need to create a new dot
if (TimeUtils.nanoTime() - lastDotTime > 1000000000) {
populateDots();
}
for (Iterator<ObjectMap.Entry<Rectangle, Texture>> iter = gameDotMap.iterator(); iter.hasNext();) {
ObjectMap.Entry<Rectangle, Texture> entry = iter.next();
Rectangle dot = entry.key;
int gameSpeed = 400;
int xSpeed = calXSpeed(gameSpeed);
dot.y = dot.y - gameSpeed * Gdx.graphics.getDeltaTime();
if (dot.x < width / 2 - 64 / 2) {
dot.x = dot.x + xSpeed * Gdx.graphics.getDeltaTime();
} else if (dot.x > width / 2 - 64 / 2) {
dot.x = dot.x - xSpeed * Gdx.graphics.getDeltaTime();
}
if (dot.y + 64 < 0) {
iter.remove();
}
if (dot.overlaps(playerDotRectangle)) {
//this is where I am trying to remove the map object on collision
iter.remove();
}
}
}
LibGDX has specific types for collections, they are recommended over the JDK's collections.

libGDX ViewPort Android devices

How can i use the fitviewport or viewport? i need to fit the screen to many android devices as posible. I dont have idea how to use that, thank you for your help, if you can paste some code for me i aprecciate that...
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();
font.setColor(Color.WHITE);
font.setScale(1f);
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;
}
escala = width / widthImage;
}
Some code
https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/ViewportTest1.java
https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/ViewportTest2.java
https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/ViewportTest3.java
And the documentation
https://github.com/libgdx/libgdx/wiki/Viewports
Run the tests and you will understand the way it works.

Categories

Resources