I'm creating small balloon game. where balloons pop up randomly and disappear after a little while. When i clicked on them those i want to disappear them and show +1 instead of the balloon. When i click on the balloon, i want to deattach the balloon sprite.
My problem is when i call sprite.detachSelf() in the code, the sprite just disapears but actually the sprite hasn't being removed. It only becomes invisible. When i click again on that place the balloon appears, even after the balloon has disappear it shows +1. Which means i think the balloon hasn't deattached correctly.
Here is my code:
#Override
protected Scene onCreateScene() {
//this.mEngine.registerUpdateHandler(new FPSLogger());
scene = new Scene();
backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion,
getVertexBufferObjectManager());
backgroundSprite.setSize(CAMERA_WIDTH, CAMERA_HEIGHT);
scene.attachChild(backgroundSprite);
scene.unregisterTouchArea(backgroundSprite);
text = new Text(0, 0, font, "Score : 00",
getVertexBufferObjectManager());
scene.attachChild(text);
textTime = new Text(displayMetrics.widthPixels - 220, 0, font,
"00 : 60", getVertexBufferObjectManager());
scene.attachChild(textTime);
timer = new TimerClock(1, new TimerClock.ITimerCallback() {
TimerClock t = timer;
public void onTick() {
System.out.println("timer inside");
if (time > 0) {
time = time - 1;
System.out.println("timer inside : " + time);
scene.detachChild(textTime);
textTime = new Text(displayMetrics.widthPixels - 220, 0,
font, "00 : " + time,
getVertexBufferObjectManager());
if (time < 10) {
textTime.setColor(1, 0, 0);
}
scene.attachChild(textTime);
deleteSpriteSpawnTimeHandler(sprite);
}
else{
scene.unregisterUpdateHandler(this.t);
}
}
});
this.mEngine.registerUpdateHandler(timer);
createSpriteSpawnTimeHandler();
return scene;
}
private void deleteSpriteSpawnTimeHandler(final IEntity ball) {
TimerHandler spriteTimerHandler1;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler1 = new TimerHandler(0.5f, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler1) {
spriteTimerHandler1.reset();
deleteSprite(ball);
}
}));
}
private void gameOverSpawnTimeHandler() {
TimerHandler spriteTimerHandler1;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler1 = new TimerHandler(60, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler1) {
spriteTimerHandler1.reset();
timeDue = 0;
scene.detachChild(textComment);
textComment = new Text(CAMERA_WIDTH / 2 - 100,
CAMERA_HEIGHT / 2, font,
"Game Over...!!!",
getVertexBufferObjectManager());
textComment.setColor(1.0f, 0.0f, 0.0f);
scene.attachChild(textComment);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
String score1 = myPrefs.getString("SCORE1", "0");
String score2 = myPrefs.getString("SCORE2", "0");
int scoreInt1 = Integer.parseInt(score1);
int scoreInt2 = Integer.parseInt(score2);
System.out.println("session in" + score1 + " "
+ score2);
currScore = totalScore;
if (currScore > scoreInt1 && currScore > scoreInt2) {
prefsEditor.clear();
prefsEditor.commit();
prefsEditor.putString("SCORE1", String.valueOf(currScore));
prefsEditor.putString("SCORE2", String.valueOf(scoreInt1));
prefsEditor.commit();
} else if (currScore < scoreInt1 && currScore > scoreInt2) {
prefsEditor.clear();
prefsEditor.commit();
prefsEditor.putString("SCORE1", String.valueOf(scoreInt1));
prefsEditor.putString("SCORE2", String.valueOf(currScore));
prefsEditor.commit();
} else {
}
}
}));
}
private void createSpriteSpawnTimeHandler() {
TimerHandler spriteTimerHandler;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler = new TimerHandler(0.75f, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler) {
spriteTimerHandler.reset();
// scene.detachChild(backgroundSprite);
// scene.attachChild(backgroundSprite);
// Random Position Generator
final float xPos = MathUtils.random(50.0f,
(CAMERA_WIDTH - 50.0f));
final float yPos = MathUtils.random(75.0f,
(CAMERA_HEIGHT - 75.0f));
gameOverSpawnTimeHandler();
if (timeDue > 0) {
createSprite(xPos, yPos);
}else{
//scene.unregisterUpdateHandler(spriteTimerHandler);
}
}
}));
}
private void createSpriteTextSpawnTimeHandler() {
TimerHandler spriteTimerHandler;
final Engine e = mEngine;
this.getEngine().registerUpdateHandler(
spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true,
new ITimerCallback() {
#Override
public void onTimePassed(
final TimerHandler spriteTimerHandler) {
spriteTimerHandler.reset();
if (totalScore > 50 && totalScore < 60) {
textComment = new Text(150, 100, font,
"Ohhhh...you are doing good.",
getVertexBufferObjectManager());
textComment.setColor(1.0f, 0.0f, 0.0f);
scene.attachChild(textComment);
}
deleteSpriteSpawnTimeHandler(textComment);
// e.getScene().detachChild(backgroundSprite);
// e.getScene().attachChild(backgroundSprite);
}
}));
}
private void createSprite(final float pX, final float pY) {
sprite = new Sprite(pX, pY, this.mrball, getVertexBufferObjectManager()) {
Engine e = mEngine;
TextureRegion gball = mgball;
float x = pX;
float y = pY;
private int score = totalScore;
private Text textComment;;
#Override
public boolean onAreaTouched(
org.andengine.input.touch.TouchEvent pSceneTouchEvent,
float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) {
this.e.getScene().detachChild(this);
if (timeDue > 0) {
mBrushDrawingSound.play();
totalScore = totalScore + 1;
String score = "Score : " + totalScore;
scene.detachChild(text);
text = new Text(0, 0, font, score,
getVertexBufferObjectManager());
scene.attachChild(text);
//sprite.detachSelf();
createSpriteTextSpawnTimeHandler();
textScorePlus = new Text(x, y, font, "+1",
getVertexBufferObjectManager());
scene.attachChild(textScorePlus);
scene.unregisterTouchArea(textScorePlus);
deleteSpriteSpawnTimeHandler(textScorePlus);
}
} else if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) {
}
// e.getScene().unregisterTouchArea(sprite);
return true;
}
};
spriteBalloon.add(sprite);
sprite.setSize(100, 100);
sprite.setAlpha(0.8f);
Random randomGenerator = new Random();
red = randomGenerator.nextInt(255);
green = randomGenerator.nextInt(255);
blue = randomGenerator.nextInt(255);
sprite.setColor(red, green, blue);
scene.registerTouchArea(sprite);
scene.attachChild(sprite);
deleteSpriteSpawnTimeHandler(sprite);
}
private void deleteSprite(IEntity pBall) {
IEntity gball = pBall;
scene.detachChild(gball);;
}
When you attach, you need to detach; when you scene.registerTouchArea(sprite), you need to scene.unregisterTouchArea(sprite).
Related
How can I get started filling up text similar to this screen? Should I use a Handler and delay every character?
The background is that I am coding a mini game for Android similar to the classic Moon Patrol and now I want to create bonus for completing a checkpoint.
You can find my beta in the appstore https://play.google.com/store/apps/details?id=dev.android.buggy It is currently named "Moon Buggy". The code is available on request, right now the repo is closed source.
I put a test checkpoint at checkpoint "C" to show what I try:
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class ParallaxView extends SurfaceView implements Runnable, SurfaceHolder.Callback {
int bombed = 5;
boolean waitForTimer = false;
boolean waitForTimer2 = false;
boolean recent = true;
char checkpoint;
boolean checkp = true;
Rect fromRect1;
Rect toRect1;
Rect fromRect2;
Rect toRect2;
boolean incCheck = true;
boolean increment = false;
int numberOfshots = 1;
int[] missiles = new int[200];
int alienBombYDelta = 0;
int alienBombXDelta = 20;
int p = 7;
boolean started = false;
final int buggyXDisplacement = 50;
boolean buggyDown = false;
int jumpHeight = 0;
int xbuggy2 = 0;
boolean down2 = true;
long lastTurn2 = System.currentTimeMillis();
long lastTurn3 = System.currentTimeMillis();
boolean jump = false;
boolean shoot = false;
int index = 0;
int missileOffSetY = 0;
boolean alienReset = false;
int score = 0;
double buggyXDistance = 0;
double distanceDelta = 1.15;
double retardation = 0.5;
boolean alienFire = false;
List<Background> backgrounds;
int spacerocki, resID, explodeID, explodeID2, alienResID2;
private volatile boolean running;
private Thread gameThread = null;
Bitmap explode, buggy, alien, explode2, spacerock;
boolean alienexplode = false;
TextView tvId;
//Activity a;
// For drawing
private Paint paint;
private Canvas canvas;
private SurfaceHolder ourHolder;
// Holds a reference to the Activity
Context context;
// Control the fps
long fps = 60;
// Screen resolution
int screenWidth;
int screenHeight;
boolean bexplode = false;
boolean brake = false;
boolean scoring = false;
class BuggyExploded extends TimerTask {
public void run() {
//Log.d("## BuggyExploded", "## BuggyExploded timer task running after 2 seconds" + buggyXDistance);
//buggy = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier("vehicle",
// "drawable", context.getPackageName()));
canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
buggyXDistance = 0;
distanceDelta = 1.15;
retardation = 0.5;
jumpHeight = 0;
waitForTimer = false;
//canvas.drawBitmap(buggy, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
}
}
class SetRecent extends TimerTask {
public void run() {
recent = false;
}
}
class ResetCheckpoint extends TimerTask {
public void run() {
Background.checkpoint = 'A';
}
}
class SetAlienBombs extends TimerTask {
public void run() {
missileOffSetY = 0;
}
}
class AlienBombed extends TimerTask {
public void run() {
alienBombXDelta = 20;
alienBombYDelta = 0;
alienReset = false;
alienexplode = false;
waitForTimer2 = false;
}
}
public void surfaceCreated(SurfaceHolder holder) {
//Canvas c = getHolder().lockCanvas();
//draw();
//getHolder().unlockCanvasAndPost(c);
}
public void surfaceDestroyed(SurfaceHolder holder3) {
//Canvas c = getHolder().lockCanvas();
//draw();
//getHolder().unlockCanvasAndPost(c);
}
public void surfaceChanged(SurfaceHolder holder, int i1, int i2, int i3) {
//Canvas c = getHolder().lockCanvas();
//draw();
//getHolder().unlockCanvasAndPost(c);
}
private void update() {
// Update all the background positions
for (Background bg : backgrounds) {
bg.update(fps);
}
}
public ParallaxView(Context c, AttributeSet a) {
super(c, a);
this.context = c;
Background.checkpoint--;
this.screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
this.screenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
// Initialize our drawing objects
ourHolder = getHolder();
paint = new Paint();
// Initialize our array list
backgrounds = new ArrayList<>();
//load the background data into the Background objects and
// place them in our GameObject arraylist
backgrounds.add(new Background(
this.context,
screenWidth,
screenHeight,
"bg", 0, 120, 50));
backgrounds.add(new Background(
this.context,
screenWidth,
screenHeight,
"grass", 70, 110, 200));
//To execute the task every second after 3 s.
//Log.d("Timer", "Timer ");
resID = context.getResources().getIdentifier("vehicle",
"drawable", context.getPackageName());
explodeID = context.getResources().getIdentifier("explode",
"drawable", context.getPackageName());
explodeID2 = context.getResources().getIdentifier("explode2",
"drawable", context.getPackageName());
spacerocki = context.getResources().getIdentifier("spacerock",
"drawable", context.getPackageName());
buggy = BitmapFactory.decodeResource(context.getResources(), resID);
explode = BitmapFactory.decodeResource(context.getResources(), explodeID);
explode2 = BitmapFactory.decodeResource(context.getResources(), explodeID2);
spacerock = BitmapFactory.decodeResource(context.getResources(), spacerocki);
alienResID2 = context.getResources().getIdentifier("right_side_hdpi",
"drawable", context.getPackageName());
alien = BitmapFactory.decodeResource(context.getResources(), alienResID2);
//resume();
//pause();
//resume();
}
#Override
public void run() {
while (running) {
long startFrameTime = System.currentTimeMillis();
update();
if (alienBombXDelta > screenWidth - 250 || alienBombXDelta < 10) { // alien ship change direction
p = -p;
}
draw();
// Calculate the fps this frame
long timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
private void checkJump() {
if (System.currentTimeMillis() - lastTurn3 >= 650) { // 650 means how long the vehicle is in the air at a jump
// Change direction here
jump = false;
lastTurn3 = System.currentTimeMillis();
}
}
private void checkBuggyBombed(Bitmap b1, Bitmap b2, Bitmap explode) {
if (!recent && java.lang.Math.abs(((buggyXDisplacement + buggyXDistance) + b1.getWidth() / 2) - (alienBombXDelta + 10 + b2.getWidth() / 2)) < b1.getWidth() / 2 && java.lang.Math.abs((alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight + b1.getHeight())) < 65) {
bombed--;
missileOffSetY = 0;
checkpoint = 'A';
canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
recent = true;
waitForTimer = true;
new Timer().schedule(new BuggyExploded(), 2000);
new Timer().schedule(new SetRecent(), 10000);
new Timer().schedule(new ResetCheckpoint(), 1000);
} else {
canvas.drawText("●", alienBombXDelta + 10 + b2.getWidth() / 2, alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY, paint);
missileOffSetY = missileOffSetY + 10;
}
}
private void makeShots(Bitmap b) {
for (int i1 = 0; i1 < numberOfshots; i1++) {
// if vertical missile hits alien
if (java.lang.Math.abs(alienBombXDelta + 10 - 185 - buggyXDistance) * 2 < (b.getWidth() + 60) && java.lang.Math.abs(alienBombYDelta + screenHeight / 100 * 25 - (screenHeight / 100 * 95 - missiles[i1] - xbuggy2)) * 2 < (b.getHeight() + 60)) {
missileOffSetY = 9999;
canvas.drawBitmap(explode2, alienBombXDelta + 10, alienBombYDelta + screenHeight / 100 * 25, paint);
new Timer().schedule(new AlienBombed(), 2000);
waitForTimer2 = true;
if (!alienexplode) {
changeText();
}
alienexplode = true;
}
if (shoot) {
canvas.drawText("o", (float) (missiles[i1] + buggyXDistance), (float) (screenHeight * 0.7) - jumpHeight, paint); // add to y the jump height
canvas.drawText("o", (float) (buggyXDistance + 185), screenHeight / 110 * 95 - missiles[i1] - xbuggy2, paint);
}
if (i1 == numberOfshots - 1 && missiles[i1] > screenWidth) {
if (numberOfshots > 0) numberOfshots--;
if (index > 0) index--;
}
}
}
private void updateDeltas() {
alienBombXDelta = alienBombXDelta + p;
if (!down2)
alienBombYDelta++;
else
alienBombYDelta--;
}
private void changeDirections() {
if (System.currentTimeMillis() - lastTurn2 >= 7000) {
// Change direction here
down2 = !down2;
lastTurn2 = System.currentTimeMillis();
}
}
private void controlVelocity() {
if (!brake && buggyXDistance > 0) buggyXDistance = buggyXDistance + distanceDelta;
else if (brake && buggyXDistance > 0) buggyXDistance = buggyXDistance - retardation;
}
TextView tvId1;
private void drawDetails() {
//draw a background color
}
private void makeShots() {
for (int n = 0; n < numberOfshots; n++)
missiles[n] = missiles[n] + 20;
}
public void changeText() {
if (scoring) {
((Activity) this.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
score++;
String str = "Player 1 " + String.format("%06d", score);
// Stuff that updates the UI
tvId.setText(str);
scoring = false;
}
});
}
}
double lastTurn4 = System.currentTimeMillis();
private void checkFire() {
if (System.currentTimeMillis() - lastTurn4 >= 18500) { // 18500 means how often the alien fires
lastTurn4 = System.currentTimeMillis();
missileOffSetY = 0;
}
}
boolean checkpointComplete = false;
private void draw() {
if (ourHolder.getSurface().isValid()) {
//First we lock the area of memory we will be drawing to
canvas = ourHolder.lockCanvas();
if (checkpointComplete) {
canvas.drawColor(Color.BLACK);
paint.setTextSize(60);
paint.setColor(Color.argb(255, 255, 255, 255));
paint.setTextSize(60);
canvas.drawText("CHECKPOINT COMPLETE", (float) (screenWidth * 0.5), (float) (screenHeight * 0.45), paint);
((Activity) this.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
checkpointComplete = false;
}
}, 3000);
}
});
} else {
if (bombed == 0) //GAME OVER
{
final int duration = Toast.LENGTH_SHORT;
((Activity) this.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
bombed = 5;
score = 0;
}
}, 3000);
}
});
}
if (jump && jumpHeight < 250) {
jumpHeight = jumpHeight + 7;
} else if (jumpHeight > 0) {
jumpHeight = jumpHeight - 4;
}
if (shoot) {
xbuggy2 = xbuggy2 + 4;
}
checkFire();
checkJump();
// drawDetails();
if (canvas != null) canvas.drawColor(Color.argb(255, 0, 0, 0));
// Draw the background parallax
drawBackground(0);
// Draw the rest of the game
paint.setTextSize(60);
paint.setColor(Color.argb(255, 255, 255, 255));
checkBuggyBombed(buggy, alien, explode);
makeShots(alien);
changeDirections();
if (!waitForTimer2)
canvas.drawBitmap(alien, alienBombXDelta + 10, alienBombYDelta + screenHeight / 100 * 25, paint);
drawBackground(1);
// canvas.drawText("X", (float) (50 + buggyXDistance)+buggy.getWidth()/2, (float) (screenHeight * 0.3) - jumpHeight+buggy.getHeight(), paint);
paint.setTextSize(60);
canvas.drawText("A E J O T Z", (float) (screenWidth * 0.7), (float) (screenHeight * 0.15), paint);
// Prevent buggy from moving outside horizontal screen
if (!brake && buggyXDisplacement + buggyXDistance > screenWidth - buggy.getWidth() - 200)
buggyXDistance = screenWidth - buggy.getWidth() - 200;
//Log.d("buggyXDistance", "buggyXDistance " + buggyXDistance);
if (!waitForTimer)
canvas.drawBitmap(buggy, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
else if (bexplode)
canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
int inc = 0;
for (int i = 0; i < bombed; i++) {
canvas.drawBitmap(Bitmap.createScaledBitmap(buggy, (int) (0.75 * (buggy.getWidth() / 3)), buggy.getHeight() / 3, false), inc, 100, paint);
inc = inc + buggy.getWidth() / 3;
}
makeShots();
updateDeltas();
controlVelocity();
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
// Clean up our thread if the game is stopped
public void pause() {
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {
// Error
//e.printStackTrace();
}
}
// Make a new thread and start it
// Execution moves to our run method
public void resume() {
running = true;
gameThread = new Thread(this);
gameThread.start();
}
private void drawBackground(int position) {
// Make a copy of the relevant background
Background bg = backgrounds.get(position);
// define what portion of images to capture and
// what coordinates of screen to draw them at
// For the regular bitmap
fromRect1 = new Rect(0, 0, bg.width - bg.xClip, bg.height);
toRect1 = new Rect(bg.xClip, bg.startY, bg.width, bg.endY);
// For the reversed background
fromRect2 = new Rect(bg.width - bg.xClip, 0, bg.width, bg.height);
toRect2 = new Rect(0, bg.startY, bg.xClip, bg.endY);
// Log.d("### bg.xClip", "bg.xClip " + bg.xClip);
//draw the two background bitmaps
if (!bg.reversedFirst) {
if (canvas != null) canvas.drawBitmap(bg.bitmap, fromRect1, toRect1, paint);
if (canvas != null) canvas.drawBitmap(bg.bitmapReversed, fromRect2, toRect2, paint);
if (position == 1) { // && Background.count % 2 == 0) {
if (increment) Background.checkpoint++;
if (Background.checkpoint == 'C' && (buggyXDisplacement + buggyXDistance) < (bg.xClip) && java.lang.Math.abs((buggyXDisplacement + buggyXDistance) - (bg.xClip)) < buggy.getWidth()) { // && java.lang.Math.abs((alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) {) checkpointComplete = true;
checkpointComplete=true;
}
increment = false;
if (bg.xClip == bg.width) increment = true;
if (canvas != null) canvas.drawBitmap(spacerock, fromRect1, toRect1, paint);
paint.setTextSize(160);
if (canvas != null)
canvas.drawText(Character.toString(Background.checkpoint), bg.xClip, (float) (bg.startY * 1.4), paint);
//increment checkpoint once per what? "Background.checkpoint++;"
((Activity) this.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
tvId1.setText(Character.toString(Background.checkpoint));
}
});
if (!recent && (buggyXDisplacement + buggyXDistance) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - jumpHeight - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + buggyXDistance) - (bg.xClip)) < buggy.getWidth()) { // && java.lang.Math.abs((alienBombYDelta + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) {
canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
// Background.checkpoint = 'A';
bombed--;
recent = true;
waitForTimer = true;
bexplode = true;
canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint);
distanceDelta = 1.15;
retardation = 0.5;
jumpHeight = 0;
((Activity) this.getContext()).runOnUiThread(new Runnable() {
#Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
waitForTimer = false;
buggyXDistance = 0;
}
}, 2000);
}
});
// new Timer().schedule(new BuggyExploded(), 2000);
new Timer().schedule(new SetRecent(), 10000);
new Timer().schedule(new ResetCheckpoint(), 1000);
}
}
} else {
canvas.drawBitmap(bg.bitmap, fromRect2, toRect2, paint);
canvas.drawBitmap(bg.bitmapReversed, fromRect1, toRect1, paint);
}
}
// Because we call this from onTouchEvent, this code will be executed for both
// normal touch events and for when the system calls this using Accessibility
#Override
public boolean performClick() {
super.performClick();
launchMissile();
return true;
}
protected void launchMissile() {
missiles[index] = 350; // what does it do?
index++;
xbuggy2 = 0;
shoot = true;
}
// event listener for when the user touches the screen
#Override
public boolean onTouchEvent(MotionEvent event) {
boolean gameOver = false;
//if (paused) {
// paused = false;
//}
int action = MotionEventCompat.getActionMasked(event);
int coordX = (int) event.getX();
int coordY = (int) event.getY();
//Log.d("coordY", "coordY " + coordY);
if (coordX < 220 && jumpHeight == 0 && action == MotionEvent.ACTION_MOVE) {
jump = true;
shoot = false;
lastTurn3 = System.currentTimeMillis();
return true; // do nothing
}
if (coordX > 219 && action == MotionEvent.ACTION_DOWN) {
numberOfshots++;
performClick();
return true;
}
return true;
}
}
[
2]: https://i.stack.imgur.com/3NAmp.gif
You can follow the below code
public void setText(final String s)
{
TextView tv= (TextView) tf.getView().findViewById(R.id.textview1);
final int[] i = new int[1];
i[0] = 0;
final int length = s.length();
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
char c= s.charAt(i[0]);
Log.d("Strange",""+c);
tv.append(String.valueOf(c));
i[0]++;
}
};
final Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
handler.sendEmptyMessage(0);
if (i[0] == length - 1) {
timer.cancel();
}
}
};
timer.schedule(timerTask, 1, 500);
}
Think this will help you for sure
I recently started using the Polygons but I'm have struggle as I'm trying to make a Polygon move towards the center of my screen, although I don't know how.
Here's the code I have(What I'm trying to accomplish here is to make the balls spawn randomly by every side of the screen and make them go towards the middle of the screen to collide against a square):
public class Game extends com.badlogic.gdx.Game implements Screen{
private SpriteBatch batch;
private Texture Ball;
private Texture Up;
private OrthographicCamera cam;
private int score;
private String showScore;
private BitmapFont scoreFont;
private Sprite upSprite;
private Polygon square;
private Array<Polygon> balls1;
private Array<Polygon> balls2;
private Array<Polygon> balls3;
private Array<Polygon> balls4;
private Polygon ball1 = new Polygon();
private Polygon ball2 = new Polygon();
private Polygon ball3 = new Polygon();
private Polygon ball4 = new Polygon();
#Override
public void create(){
batch = new SpriteBatch();
Ball = new Texture("energyball.png");
Up = new Texture("up.png");
upSprite = new Sprite(Up);
upSprite.setOriginCenter();
upSprite.setX(615);
upSprite.setY(340);
upSprite.setRegionWidth(64);
upSprite.setRegionHeight(64);
square = new Polygon(new float[] {
upSprite.getX(), upSprite.getY(),
upSprite.getX(), upSprite.getY() + upSprite.getHeight(),
upSprite.getX() + upSprite.getWidth(), upSprite.getY() + upSprite.getY(),
upSprite.getX() + upSprite.getWidth(), upSprite.getY()
});
cam = new OrthographicCamera();
cam.setToOrtho(false, 1280, 720);
upSprite.setPosition(upSprite.getX(), upSprite.getY());
square.setOrigin(upSprite.getX(), upSprite.getY());
// calls the functions to spawn balls randomly
balls1 = new Array<Polygon>();
balls2 = new Array<Polygon>();
balls3 = new Array<Polygon>();
balls4 = new Array<Polygon>();
score();
//if the screen is touched sprite rotates 90 degrees clockwise
Gdx.input.setInputProcessor(new InputAdapter() {
#Override
public boolean touchDown(int x, int y, int pointer, int button) {
return true;
}
#Override
public boolean touchUp(int x, int y, int pointer, int button) {
upSprite.rotate(-90);
square.rotate(-90f);
return true;
}
});
}
//shows score
private void score() {
score = -4;
showScore = "Score: 0";
scoreFont = new BitmapFont();
}
//creates the balls and sets their position as well as the random timer for each
private void spawnBalls1() {
ball1.setPosition(MathUtils.random(639, 641), 720);
ball1.setScale(32, 32);
balls1.add(ball1);
lastDropTime = TimeUtils.nanoTime();
}
private void spawnBalls2() {
ball2.setPosition(0, MathUtils.random(359, 361));
ball2.setScale(32, 32);
balls2.add(ball2);
lastDropTime = TimeUtils.nanoTime();
}
private void spawnBalls3() {
ball3.setPosition(MathUtils.random(639, 641), 0);
ball3.setScale(32, 32);
balls3.add(ball3);
lastDropTime = TimeUtils.nanoTime();
}
private void spawnBalls4() {
ball4.setPosition(1280, MathUtils.random(359, 361));
ball4.setScale(32, 32);
balls4.add(ball4);
lastDropTime = TimeUtils.nanoTime();
}
#Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.update();
//draws the game itself as well as the balls on the screen
batch.setProjectionMatrix(cam.combined);
batch.begin();
upSprite.draw(batch);
//draws the balls
for (Polygon ball1 : balls1) {
batch.draw(Ball, ball1.getX(), ball1.getY());
}
for (Polygon ball2 : balls2) {
batch.draw(Ball, ball2.getX(), ball2.getY());
}
for (Polygon ball3 : balls3) {
batch.draw(Ball, ball3.getX(), ball3.getY());
}
for (Polygon ball4 : balls4) {
batch.draw(Ball, ball4.getX(), ball4.getY());
}
scoreFont.setColor(1, 1, 1, 1);
scoreFont.draw(batch, showScore, 25, 100);
batch.end();
// if the time minus the time of the last ball spawn is less than x then spawn another ball in a random place
if (TimeUtils.nanoTime() - lastDropTime > 1000000000) {
switch (MathUtils.random(4)) {
case 0:
spawnBalls1();
break;
case 1:
spawnBalls2();
break;
case 2:
spawnBalls3();
break;
case 3:
spawnBalls4();
break;
}
}
Iterator<Polygon> iter1 = balls1.iterator();
while(iter1.hasNext()) {
Polygon balls1 = iter1.next();
balls1.getY() -= 350 * Gdx.graphics.getDeltaTime();
if (Intersector.overlapConvexPolygons(balls1, square)) {
score++;
showScore = "Score: " + score;
iter1.remove();
}
}
Iterator<Polygon> iter2 = balls2.iterator();
while (iter2.hasNext()) {
Polygon balls2 = iter2.next();
balls2.x += 550 * Gdx.graphics.getDeltaTime();
if (Intersector.overlapConvexPolygons(balls2, square)) {
score++;
showScore = "Score: " + score;
iter2.remove();
}
}
Iterator<Polygon> iter3 = balls3.iterator();
while(iter3.hasNext()) {
Polygon balls3 = iter3.next();
balls3.y += 350 * Gdx.graphics.getDeltaTime();
if (Intersector.overlapConvexPolygons(balls3, square)) {
score++;
showScore = "Score: " + score;
iter3.remove();
}
}
Iterator<Polygon> iter4 = balls4.iterator();
while(iter4.hasNext()) {
Polygon balls4 = iter4.next();
balls4.x -= 550 * Gdx.graphics.getDeltaTime();
if (Intersector.overlapConvexPolygons(balls4, square)) {
score++;
showScore = "Score: " + score;
iter4.remove();
}
}
}
And I'm getting an error here:
balls1.getY() -= 350 * Gdx.graphics.getDeltaTime();
balls2.getX() += 550 * Gdx.graphics.getDeltaTime();
balls3.getY() += 350 * Gdx.graphics.getDeltaTime();
balls4.getX() -= 550 * Gdx.graphics.getDeltaTime();
Any help would be gladly appreciated.
I have encountered the problem with my buttons. My code is as follows.
public class rarsterinco implements ApplicationListener {
Texture background;
Texture background2;
Texture background3;
Vector2 backgroundmove;
Vector2 backgroundmove2;
SpriteBatch batch;
Rectangle bounds;
CharSequence line = "got touched."; // = myScore;
Rectangle bounds2;
boolean check;
boolean collision;
int beginning;
CharSequence headup = "got touched";
Vector2 pos;
Vector2 position;
Vector2 size;
Vector2 size2;
BitmapFont font;
Texture mysteryCloud;
Texture mario;
Texture water;
Vector2 watermove;
Vector2 watersize;
Stage stage;
TextureAtlas buttonAtlas;
TextButtonStyle buttonStyle;
TextButton button;
Skin skin;
#Override
public void create() {
BitmapFont font = new BitmapFont();
skin = new Skin();
buttonAtlas = new TextureAtlas("buttons/pause.pack");
skin.addRegions(buttonAtlas);
buttonStyle = new TextButtonStyle();
buttonStyle.up = skin.getDrawable("imgres");
buttonStyle.over = skin.getDrawable("imgres");
buttonStyle.down = skin.getDrawable("imgres");
button = new TextButton("", buttonStyle);
stage.addActor(button);
mysteryCloud = new Texture(Gdx.files.internal("data/mysteryCloud.jpg"));
batch = new SpriteBatch();
mario = new Texture(Gdx.files.internal("data/mario.jpg"));
background = new Texture(Gdx.files.internal("data/background1.jpg"));
background2 = new Texture(Gdx.files.internal("data/background2.jpg"));
background3 = new Texture(Gdx.files.internal("data/background3.jpg"));
position = new Vector2();
pos = new Vector2();
backgroundmove = new Vector2();
backgroundmove2 = new Vector2();
size2 = new Vector2(mario.getWidth() ,mario.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(mysteryCloud.getWidth() ,mysteryCloud.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, 32, 32);
}
#Override
public void dispose() {
//font.dispose();
}
public void update(){
bounds.set(pos.x, pos.y, 32, 32);
bounds2.set(position.x, position.y, size2.x, size2.y);
position.x = position.x + 5* Gdx.input.getAccelerometerY();
//float pos1=Gdx.input.getAccelerometerY();
//position.x = position.x - 5*pos1;
//float pos2=Gdx.input.getAccelerometerY();
//position.y = position.y - 5*pos2;
}
#Override
public void render() {
beginning = beginning+ 1;
if(beginning == 1){
backgroundmove.x = Gdx.graphics.getWidth();
}
position.y = position.y -10;
if(position.x<0){
Gdx.input.vibrate(250);
}
if(position.x>Gdx.graphics.getWidth()){
Gdx.input.vibrate(250);
}
//if(position.y<0){
//Gdx.input.vibrate(250);
//}
if(position.y>Gdx.graphics.getHeight()){
Gdx.input.vibrate(250);
}
if(bounds.overlaps(bounds2)){
collision=true;
}else{
collision= false;
}
if(position.x<0){
position.x= position.x+80;
}
if(position.x>Gdx.graphics.getWidth() - mario.getWidth()){
position.x= position.x-80;
}
if(Gdx.input.isTouched()){
position.y = position.y + 30;
}
if(position.y<0){
position.y= position.y+80;
}
if(position.y>Gdx.graphics.getWidth() +mario.getHeight()){
position.y= position.y-80;
}
pos.x = pos.x - 10;
if(pos.x <0 && collision == false){
pos.x = Gdx.graphics.getWidth();
Random randomGenerator = new Random();
pos.y = randomGenerator.nextInt(Gdx.graphics.getHeight()-30);
}
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(Gdx.input.getAccelerometerX() == 10){
}
if(collision){
pos.x = Gdx.graphics.getWidth();
Random randomGenerator = new Random();
pos.y = randomGenerator.nextInt(Gdx.graphics.getHeight()-30);
}
backgroundmove.x = backgroundmove.x - 10;
backgroundmove2.x = backgroundmove2.x - 10;
if(backgroundmove.x <-Gdx.graphics.getWidth()){
backgroundmove.x = Gdx.graphics.getWidth();
}
if(backgroundmove2.x <-Gdx.graphics.getWidth()){
backgroundmove2.x = Gdx.graphics.getWidth();
}
update();
batch.begin();
// if(!collision){
// batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
// }
// batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
// if(collision){
// mysteryCloud.dispose();
// }
// if(pos.x<0 && collision == true){
// batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
// }
//
//batch.draw(background3, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//batch.draw(background, backgroundmove.x, backgroundmove.y, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
//batch.draw(background2, backgroundmove2.x, backgroundmove2.y, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(mario, position.x,position.y);
batch.draw(mysteryCloud, pos.x, pos.y, 64, 64);
font.setScale(4);
font.setColor(0.0f, 1.0f, 1.0f,1.0f);
stage.draw();
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
What I realized was that when I commented the stage.draw() and the other button code my app worked, but when I uncommented the code it said mylibgdxgame has stopped working.
The button code is as follows:
TextureAtlas buttonAtlas;
TextButtonStyle buttonStyle;
TextButton button;
Skin skin;
#Override
public void create() {
BitmapFont font = new BitmapFont();
skin = new Skin();
buttonAtlas = new TextureAtlas("buttons/pause.pack");
skin.addRegions(buttonAtlas);
buttonStyle = new TextButtonStyle();
buttonStyle.up = skin.getDrawable("imgres");
buttonStyle.over = skin.getDrawable("imgres");
buttonStyle.down = skin.getDrawable("imgres");
button = new TextButton("", buttonStyle);
stage.addActor(button);
,
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: No Drawable, NinePatch, TextureRegion, Texture, or Sprite registered with name: imgres at com.badlogic.gdx.scenes.scene2d.ui.Skin.getDrawable(Skin.java:291) at com.me.rarsterinco.rarsterinco.create(rarsterinco.java:64) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: Missing LabelStyle font. at com.badlogic.gdx.scenes.scene2d.ui.Label.setStyle(Label.java:77) at com.badlogic.gdx.scenes.scene2d.ui.Label.<init>(Label.java:71) at com.badlogic.gdx.scenes.scene2d.ui.TextButton.<init>(TextButton.java:48) at com.me.rarsterinco.rarsterinco.create(rarsterinco.java:69) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:136) at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
How can i create a textPaint as a count down timer to control the game end?
I have tried to use countDownTimer with drawText to do something like that,it can show in surfaceview but it doesn't update for each onTick.
public class CfView extends SurfaceView {
/** The activity object. */
private final Activity activity;
/** The answer object. */
private static Answer answer;
private static int score;
/** The InputPanel object. */
private static InputPanel inputPanel;
/** The AnswerPanel object. */
private static AnswerPanel answerPanel;
/** Keyboard panel height. */
private static final float INPUT_PANEL_HEIGHT_WEIGHT = 0.7f;
/** Answer panel height. */
private static final float ANSWER_PANEL_HEIGHT_WEIGHT = 0.3f;
private Timer timer;
private String countDownTime;
private boolean gameOver;
private UserInput userInput = new UserInput();
private CountDownTimer cdTimer;
/** Saving and handling of user input of touch events. */
private class UserInput {
/** Whether there is a user input present. */
boolean present = false;
/** Action of the user input {#link MotionEvent}. */
int action;
/** x, y positions of the user input {#link MotionEvent}. */
int x, y;
synchronized void save(MotionEvent event) {
present = true;
action = event.getAction();
x = (int) event.getX();
y = (int) event.getY();
handle();
}
synchronized void handle() {
int pos = -1;
if (present) {
cdTimer.start();
if (action == MotionEvent.ACTION_UP) {
int[] clickedBallData = inputPanel.checkballStroked(x, y);
if (clickedBallData != null) {
pos = clickedBallData[0];
int value = clickedBallData[1];
if (answer.isCorrect(value)) {
if (answer.isHCF(value)) {
score += 500;
} else {
score += 100;
}
} else {
score -= 100;
if (score < 0)
score = 0;
}
inputPanel.updateInputPanel(pos, answer);
}
}
drawGameComponent();
present = false;
}
}
}
private class AnimationTask extends TimerTask {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d("thread", "run");
userInput.handle();
Canvas canvas = getHolder().lockCanvas();
if (canvas != null) {
answerPanel.drawOn(canvas);
inputPanel.drawOn(canvas);
Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(50);
textPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Score : " + score, getWidth() * 0.7f, 50,
textPaint);
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(50);
textPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText("Time : " + countDownTime + "s", 0, 50,
textPaint);
if (gameOver) {
textPaint.setTextSize(2 * 30);
textPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Times up", getWidth() / 2,
getHeight() / 2, textPaint);
canvas.drawText("Score : " + score, getWidth() / 2,
getHeight() / 2 + (2 * 30), textPaint);
}
getHolder().unlockCanvasAndPost(canvas);
}
}
}
public CfView(Activity activity) {
super(activity);
setFocusableInTouchMode(true); // For getting key events
cdTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
countDownTime = String.valueOf(millisUntilFinished / 1000);
invalidate();
}
public void onFinish() {
countDownTime = 0 + "";
gameOver = true;
cancel();
}
};
setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
userInput.save(event);
return true;
}
});
this.activity = activity;
timer = new Timer();
timer.schedule(new AnimationTask() {
#Override
public void run() {
while (getWidth() == 0)
; // Wait for layout
newGame(true);
}
}, 0);
}
public void resume() {
if (timer == null)
timer = new Timer();
timer.schedule(new AnimationTask(), 0, 0);
}
public void pause() {
timer.cancel();
timer = null;
}
private void drawGameComponent() {
Canvas canvas = getHolder().lockCanvas();
if (canvas != null) {
answerPanel.drawOn(canvas);
inputPanel.drawOn(canvas);
Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(50);
textPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Score : " + score, getWidth() * 0.7f, 50,
textPaint);
getHolder().unlockCanvasAndPost(canvas);
}
}
public void drawTimeText() {
Canvas canvas = getHolder().lockCanvas();
Paint textPaint = new Paint();
if (canvas != null) {
textPaint.setColor(Color.BLACK);
textPaint.setTextSize(50);
textPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText("Time : " + countDownTime + "s", 0, 50, textPaint);
if (gameOver) {
textPaint.setTextSize(2 * 30);
textPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Times up", getWidth() / 2, getHeight() / 2,
textPaint);
canvas.drawText("Score : " + score, getWidth() / 2, getHeight()
/ 2 + (2 * 30), textPaint);
}
getHolder().unlockCanvasAndPost(canvas);
}
}
public void newGame(boolean newGame) {
score = 0;
gameOver = false;
if (newGame) {
answer = new Answer(activity);
Log.d("CF", getHeight() + ";" + getWidth());
answerPanel = new AnswerPanel(activity, 0, 0, getWidth(),
(int) (getHeight() * ANSWER_PANEL_HEIGHT_WEIGHT), answer);
inputPanel = new InputPanel(activity, 0,
(int) (getHeight() * (ANSWER_PANEL_HEIGHT_WEIGHT)),
getWidth(), (int) (getHeight()), answer);
} else {
answer.newNumber();
inputPanel.resetInputPanel();
answerPanel.resetAnswerPanel(answer);
}
drawGameComponent();
}
public void updateCategory(Answer.Level level) {
answer.updateCategory(level);
newGame(false);
}
#Override
protected boolean verifyDrawable(Drawable who) {
return true;
}
#Override
public void invalidateDrawable(Drawable drawable) {
}
}
I have been making a game and lately i have had a problem of making an image disappear. My code is as follows
package com.me.fixGame;
import java.util.Random;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
//import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.Scaling;
import com.sun.jmx.snmp.tasks.Task;
public class fixGame implements ApplicationListener {
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture trash;
Texture paper;
SpriteBatch spritebatch;
Vector2 position;
Vector2 pas;
boolean collide;
boolean countMe=false;
Vector2 size;
Vector2 size2;
Vector2 pos;
Rectangle bounds;
Rectangle bounds2;
float delay = 1; // seconds
boolean counted= false;
int score = 3;
//Texture Gogreen;
String myScore;
Texture background;
CharSequence str = "Lives left: 3"; // = myScore;
CharSequence line = "Score: 0"; // = myScore;
String myLife;
int life=0;
BitmapFont font;
float x;
float y;
boolean collision = false;
#Override
public void create() {
//Gogreen = new Texture(Gdx.files.internal("data/gogreenNow.jpg"));
background = new Texture(Gdx.files.internal("data/trash.png"));
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
size2 = new Vector2(trash.getWidth() ,trash.getHeight() );
//size2.y = trash.getHeight();
//size2.x = trash.getWidth();
size = new Vector2(paper.getWidth() ,paper.getHeight());
bounds= new Rectangle(pos.x, pos.y, size.x, size.y);
bounds2= new Rectangle(position.x, position.y, size2.x, size2.y);
}
#Override
public void dispose() {
}
public void update(){
bounds.set(pos.x, pos.y, size.x, size.y);
bounds2.set(position.x, position.y, size2.x, size2.y);
position.x = position.x -2- Gdx.input.getAccelerometerX();
}
#Override
public void render() {
if(bounds.overlaps(bounds2)){
collision=true;
counted=true;
}else{
collision=false;
}
if(collision==true){
}
if(pos.y<640){
counted=false;
} else if(pos.y > 640 && collision==false && counted==false){
counted=true;
score= score-1;
myScore = "Lives left: " + score;
str = myScore;
}
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
if(position.x<0){
position.x= position.x+11;
}
if(position.x>425){
position.x= position.x-11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y=pos.y-12;
if(pos.y<0){
pos.y = 700;
Random randomGenerator = new Random();
pos.x = randomGenerator.nextInt(500);
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.draw(paper, pos.x, pos.y);
batch.draw(trash, position.x, position.y);
font.setScale(3);
font.setColor(0.0f, 0.0f, 1.0f,1.0f);
font.draw(batch, str, 200,900);
font.draw(batch, line, 200, 700);
batch.end();
font.dispose();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
I want to make my image called paper to disappear which I instantiate here.
x= background.getWidth();
y=background.getHeight();
//float delaySeconds = 1;
spriteBatch = new SpriteBatch();
trash = new Texture(Gdx.files.internal("data/trash.png"));
paper = new Texture(Gdx.files.internal("data/paper1.jpg"));
position = new Vector2(100, 50);
pos = new Vector2(54, 14);
batch = new SpriteBatch();
BitmapFont font = new BitmapFont();
And where i want it to disappear is below:
if(bounds.overlaps(bounds2)){
countMe=true;
life= life+50;
myLife = "Score: " + life;
line = myLife;
}
What i want to do is when the two objects overlap(bounds and bounds2) the score should be changed and one of the objects, the paper, should hide. How do i make an image hide?
Becuase you already are setting the collision state to a variable, in the render() method you just need to wrap the batch.draw() method. I've tested this code and it works. You also need to set collision to false when you set the paper back to the top, I'm guessing you want it to hide completely until it resets. Please note I've also made some small tweaks just so it's easier to test. If there are still runtime bugs it's not related to this change.
#Override
public void render() {
if (bounds.overlaps(bounds2)) {
collision = true;
counted = true;
}
if (pos.y < 640) {
counted = false;
} else if (pos.y > 640 && collision == false && counted == false) {
counted = true;
score = score - 1;
myScore = "Lives left: " + score;
str = myScore;
}
if (bounds.overlaps(bounds2)) {
countMe = true;
life = life + 50;
myLife = "Score: " + life;
line = myLife;
}
if (position.x < 0) {
position.x = position.x + 11;
}
if (position.x > 425) {
position.x = position.x - 11;
}
update();
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
pos.y = pos.y - 2;
if (pos.y < 0) {
pos.y = 700;
Random randomGenerator = new Random();
pos.x = 250;
collision = false;
}
BitmapFont font = new BitmapFont();
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
if (!collision) {
batch.draw(paper, pos.x, pos.y);
}
batch.draw(trash, position.x, position.y);
font.setScale(1.5f);
font.setColor(0.0f, 0.0f, 1.0f, 1.0f);
font.draw(batch, str, 20, 50);
font.draw(batch, line, 20, 100);
batch.end();
font.dispose();
}