Save currentTime as long (AndroidStudio/libgdx - java

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

Related

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.

How to insert a button using Java Based Program in Eclipse

I just want to ask how to create a button using java based program. I want to have a button on my official game like Next button that if the user clicked it, it will allow them to go to the next level of the game. It's like a pause/resume/stop/restart button inside the game.
This is the code of the Game I used. I can't see the declaration of button here but when I played this, it has a exit button(?) above that allows the user to go back to previous form.
public class NewGame extends Activity {
static MediaPlayer mp1;
MediaPlayer jump;
MediaPlayer takecoin;
GameLoopThread gameLoopThread;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for no title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GameView(this));
}
public class GameView extends SurfaceView {
Bitmap bmp;
Bitmap background, taya, note1;
Bitmap run1;
Bitmap run6;
Bitmap jump2;
Bitmap coin;
Bitmap exit;
// MediaPlayer mp1,jump,takecoin;
private SurfaceHolder holder;
// private gameloop gameLoopThread;
private int x = 0, y = 0, z = 0, delay = 0, getx, gety, sound = 1;
int show = 0, sx, sy = 0;
int cspeed = 0, kspeed = 0, gameover = 0;
int score = 0, health = 120, reset = 0;
private int min = 1, sec = 0;
private Handler mHandler = new Handler();
private Runnable mRunnable;
private boolean isStop = false;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public GameView(Context context) {
super(context);
mHandler.postDelayed(mRunnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(sec <= 0){
if(min > 0){
sec = 59;
min--;
isStop = false;
}
else{
//stop timer here
Log.e("TIMER", "timer stop!");
mHandler.removeCallbacks(this);
isStop = true;
}
}
else{
sec--;
isStop = false;
}
Log.i("TIMER", "min: " + min + " sec: " + sec);
if(!isStop){
mHandler.postDelayed(this, 1000);
}
}
}, 1000);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#SuppressWarnings("deprecation")
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// for stoping the game
gameLoopThread.setRunning(false);
gameLoopThread.getThreadGroup().interrupt();
}
#SuppressLint("WrongCall")
#Override
public void surfaceCreated(SurfaceHolder holder) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
// getting the screen size
Display display = getWindowManager().getDefaultDisplay();
sx = display.getWidth();
sy = display.getHeight();
;
cspeed = x / 4;
kspeed = x / 4;
background = BitmapFactory.decodeResource(getResources(),
R.drawable.imgluneta);
run1 = BitmapFactory
.decodeResource(getResources(), R.drawable.run1);
run6 = BitmapFactory
.decodeResource(getResources(), R.drawable.run6);
jump2 = BitmapFactory.decodeResource(getResources(),
R.drawable.run11);
coin = BitmapFactory
.decodeResource(getResources(), R.drawable.coin);
exit = BitmapFactory
.decodeResource(getResources(), R.drawable.exit);
taya = BitmapFactory
.decodeResource(getResources(), R.drawable.taya);
note1 = BitmapFactory.decodeResource(getResources(),
R.drawable.note1);
exit = Bitmap.createScaledBitmap(exit, 25, 25, true);
background = Bitmap
.createScaledBitmap(background, 2 * sx, sy, true);
// health dec
note1 = Bitmap.createScaledBitmap(note1, sx, sy, true);
mp1 = MediaPlayer.create(NewGame.this, R.raw.game);
jump = MediaPlayer.create(NewGame.this, R.raw.jump);
takecoin = MediaPlayer.create(NewGame.this, R.raw.cointake);
}
// on touch method
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
show = 1;
getx = (int) event.getX();
gety = (int) event.getY();
// exit
if (getx < 25 && gety < 25) {
System.exit(0);
}
// sound off
if (getx > 25 && getx < 60) {
if (gety < 25) {
sound = 0;
mp1.stop();
}
}
// sound on
if (getx > 61 && getx < 90) {
if (gety < 25) {
sound = 1;
}
}
// restart game
if (getx > 91 && gety < 25) {
if (health <= 0) {
gameLoopThread.setPause(0);
health = 100;
score = 0;
}
}
}
return true;
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
// background moving
z = z - 10;
if (z == -sx) {
z = 0;
canvas.drawBitmap(background, z, 0, null);
} else {
canvas.drawBitmap(background, z, 0, null);
}
// running player
x += 5;
if (x == 20) {
x = 5;
}
if (show == 0) {
if (x % 2 == 0) {
int height = run1.getHeight();
canvas.drawBitmap(run1, sx / 16, (15 * sy / 18) - height / 2, null);
// kinfe hit
if (kspeed == 20) {
kspeed = sx;
health -= 25;
canvas.drawBitmap(note1, 0, 0, null);
}
} else {
int height = run6.getHeight();
canvas.drawBitmap(run6, sx / 16, (15 * sy / 18) - height / 2, null);
// kinfe hit
if (kspeed == 20) {
kspeed = sx / 2;
health -= 25;
canvas.drawBitmap(note1, 0, 0, null);
}
}
}
// for jump
if (show == 1) {
if (sound == 1) {
jump.start();
}
int height=jump2.getHeight();
canvas.drawBitmap(jump2, sx / 16, (3 * sy / 4)-height, null);
// score
if (cspeed <= (sx / 8)-height/2 && cspeed >= (sx / 16)-height/2) {
if (sound == 1) {
takecoin.start();
}
cspeed = sx / 2;
score += 10;
}
// jump-hold
delay += 1;
if (delay == 3) {
show = 0;
delay = 0;
}
}
// for coins
cspeed = cspeed - 5;
if (cspeed == -sx / 2) {
cspeed = sx / 2;
canvas.drawBitmap(coin, cspeed, 3 * sy / 4, null);
} else {
canvas.drawBitmap(coin, cspeed, 3 * sy / 4, null);
}
// kinfe
kspeed = kspeed - 20;
int height = taya.getHeight();
canvas.drawBitmap(taya, kspeed, (15 * sy / 18) - height / 2, null);
if (kspeed < 0) {
kspeed = sx;
health -= 25;
}
// score
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
paint.setTextSize(15);
paint.setTextAlign(Align.LEFT);
canvas.drawText("Score :" + score, 3 * sx / 4, 20, paint);
// exit
canvas.drawBitmap(exit, 0, 0, null);
if (sound == 1) {
mp1.start();
mp1.setLooping(true);
}
// health
Paint myPaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
canvas.drawText("Health :" + health, 0, (sy / 8) - 5, myPaint);
canvas.drawRect(0, sy / 8, health, sy / 8 + 10, myPaint);
// game over
if (health <= 0) {
gameover = 1;
mp1.stop();
canvas.drawText("GAMEOVER OVER", sx / 2, sy / 2, myPaint);
canvas.drawText("YOUR SCORE : " + score, sx / 2, sy / 4,
myPaint);
canvas.drawText("Restart", 91, 25, myPaint);
gameLoopThread.setPause(1);
}
// restart
if (reset == 1) {
gameLoopThread.setPause(0);
health = 100;
score = 0;
}
// timer
Paint mypaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
mypaint.setTextSize(50);
canvas.drawText("Timer :" + min + sec,min, sec, mypaint);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onResume() {
super.onResume();
NewGame.mp1.isPlaying();
}
#Override
public void onPause() {
super.onPause();
NewGame.mp1.pause();
}
}
You can create a button in Java code-
Button button = new Button(this);
where 'this' is context.

libGDX consult with speed

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

java game - slick - collision handling

How can I manage collisions in slick ?
I created map and every tile which is wall have option blocked = true;
How to implement collision, that if I hit wall, I can move trough it?
Also if I reach edge of map, block movement.
package javagame;
import org.newdawn.slick.Animation;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.tiled.TiledMap;
public class Play extends BasicGameState {
Animation movingUp, movingDown, movingLeft, movingRight;
Animation player;
int[] duration = {200, 200, 200};
float playerX = 0;
float playerY = 0;
float cameraX;
float cameraY;
float screenWidth;
float screenHeight;
private TiledMap map = null;
private static final float SPEED = 0.1f;
private boolean[][] blocked;
public Play(int state, int x, int y) {
playerX = (float) x;
playerY = (float) y;
}
private boolean blocked(float x, float y) {
return blocked[(int) x][(int) y];
}
#Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
map = new TiledMap("map/map.tmx");
// build a collision map based on tile properties in the TileD map
blocked = new boolean[map.getWidth()][map.getHeight()];
for (int x = 0; x < map.getWidth(); x++) {
for (int y = 0; y < map.getHeight(); y++) {
int tileID = map.getTileId(x, y, 0);
String value = map.getTileProperty(tileID, "blocked", "false");
if ("true".equals(value)) {
blocked[x][y] = true;
}
}
}
Image[] walkUp = {
new Image("graphics/player/up0.png"),
new Image("graphics/player/up1.png"),
new Image("graphics/player/up2.png")
};
Image[] walkDown = {
new Image("graphics/player/down0.png"),
new Image("graphics/player/down1.png"),
new Image("graphics/player/down2.png")
};
Image[] walkLeft = {
new Image("graphics/player/left0.png"),
new Image("graphics/player/left1.png"),
new Image("graphics/player/left2.png")
};
Image[] walkRight = {
new Image("graphics/player/right0.png"),
new Image("graphics/player/right1.png"),
new Image("graphics/player/right2.png")
};
movingUp = new Animation(walkUp, duration, false);
movingDown = new Animation(walkDown, duration, false);
movingLeft = new Animation(walkLeft, duration, false);
movingRight = new Animation(walkRight, duration, false);
player = movingDown;
}
#Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
screenWidth = gc.getWidth();
screenHeight = gc.getHeight();
cameraX = (screenWidth / 2) - (playerX / 2);
cameraY = (screenHeight / 2) - (playerY / 2);
map.render((int) playerX, (int) playerY);
player.draw(cameraX, cameraY);
g.drawString("X: " + playerX + "\nY: " + playerY, 520, 20);
g.resetTransform();
}
#Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)) {
player = movingUp;
playerY += delta * SPEED;
player.update(delta);
} else if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)) {
player = movingDown;
playerY -= delta * SPEED;
player.update(delta);
} else if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A)) {
player = movingLeft;
playerX += delta * SPEED;
player.update(delta);
} else if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D)) {
player = movingRight;
playerX -= delta * SPEED;
player.update(delta);
}
}
}
Here is sample source code (NetBeans project):
https://www.box.com/s/9nicp0n067de632kcpj3
On Update, you can simply check the array. If it is a wall don't update. If it is the border, don't update.
#Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
float yChange = 0, xChange=0;
boolean capturedInput = false;
if (input.isKeyDown(Input.KEY_UP) || input.isKeyDown(Input.KEY_W)) {
player = movingUp;
yChange += delta * SPEED;
capturedInput = true;
} else if (input.isKeyDown(Input.KEY_DOWN) || input.isKeyDown(Input.KEY_S)) {
player = movingDown;
yChange -= delta * SPEED;
capturedInput = true;
} else if (input.isKeyDown(Input.KEY_LEFT) || input.isKeyDown(Input.KEY_A)) {
player = movingLeft;
xChange += delta * SPEED;
capturedInput = true;
} else if (input.isKeyDown(Input.KEY_RIGHT) || input.isKeyDown(Input.KEY_D)) {
player = movingRight;
xChange -= delta * SPEED;
capturedInput = true;
}
if(capturedInput==true && !blocked(playerX+xChange,playerY+yChange)){
playerX += xChange;
playerY += yChange;
player.update(delta);
}
}
private boolean blocked(float x, float y) {
return blocked[(int) x][(int) y];
}
Pretty much, do not change the value until you check it first and then change the player value if all is okay.
EDIT: I added a variable capturedInput, this will let me know that we actually have a keyDown event. There are two comments about this. I consider this a "hack" to make your code work and not the most beautiful. I would personally try to add an event listener to the window to listen for key clicks, when a key is clicked I would change the position information, all the while the frame is refreshing and will update, or only refresh now that there was a change by calling repaint().
There are lots of tutorials out there for listening to onKeyDown. Your code should work better now and won't need the manual catch for the edge like your doing, you should be able to draw a wall around the edge in the block array of booleans, if not you can continue with your method.
Try creating a Rectangle of your blocks from X and Y position multiplied by tile dimensions and then verify with the intersects() method if it collides with your entity, such as explained in wiki Slick.
I hope that's useful to you.

java game - slick scroller - player can't move

My scroller is working but I can't move player.
Player is centering to middle of window screen. And map is centering to player's position.
Window (program) size is 640 x 640 px
Map map.tmx is orthogonal (zelda/pokemon style game).
Using only UP, DOWN, RIGHT, LEFT keys (no diagonal moves).
what I am calculating or doing bad ?
public class Play extends BasicGameState {
Animation movingUp, movingDown, movingLeft, movingRight;
Animation player;
String playerName = "Test";
boolean quit = false;
int[] duration = {200, 200, 200};
int playerX = 0;
int playerY = 0;
int cameraX;
int cameraY;
int screenWidth;
int screenHeight;
private TiledMap map = null;
private static final float SPEED = 0.1f;
public Play(int state, float x, float y) {
playerX = (int) x;
playerY = (int) y;
}
#Override
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
map = new TiledMap("map/map.tmx");
Image[] walkUp = {
new Image("graphics/player/up0.png"),
new Image("graphics/player/up1.png"),
new Image("graphics/player/up2.png")
};
Image[] walkDown = {
new Image("graphics/player/down0.png"),
new Image("graphics/player/down1.png"),
new Image("graphics/player/down2.png")
};
Image[] walkLeft = {
new Image("graphics/player/left0.png"),
new Image("graphics/player/left1.png"),
new Image("graphics/player/left2.png")
};
Image[] walkRight = {
new Image("graphics/player/right0.png"),
new Image("graphics/player/right1.png"),
new Image("graphics/player/right2.png")
};
movingUp = new Animation(walkUp, duration, false);
movingDown = new Animation(walkDown, duration, false);
movingLeft = new Animation(walkLeft, duration, false);
movingRight = new Animation(walkRight, duration, false);
player = movingDown;
}
#Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
screenWidth = gc.getWidth();
screenHeight = gc.getHeight();
cameraX = (screenWidth / 2) - (playerX / 2);
cameraY = (screenHeight / 2) - (playerY / 2);
map.render(playerX, playerY);
player.draw(cameraX, cameraY);
g.drawString("X: " + playerX + "\nY: " + playerY, 520, 20);
g.resetTransform();
}
#Override
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_UP)) {
player = movingUp;
player.update(delta);
playerY += delta * SPEED;
} else if (input.isKeyDown(Input.KEY_DOWN)) {
player = movingDown;
player.update(delta);
playerY -= delta * SPEED;
} else if (input.isKeyDown(Input.KEY_LEFT)) {
player = movingLeft;
player.update(delta);
playerX += delta * SPEED;
} else if (input.isKeyDown(Input.KEY_RIGHT)) {
player = movingRight;
player.update(delta);
playerX -= delta * SPEED;
}
}
}
Basic idea:
screenWidth = gc.getWidth();
screenHeight = gc.getHeight();
cameraX = (screenWidth / 2) - (playerX / 2);
cameraY = (screenHeight / 2) - (playerY / 2);
map.render(playerX, playerY);
player.draw(cameraX, cameraY);
Working in my example

Categories

Resources