How to make an image disappear using libgdx - android

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

Related

Android Opencv save mat as a picture without drawn rectangle

I want to save a Mat mRgba as a picture with Imgcodecs.imwrite(Environment.getExternalStorageDirectory() + "/final-image.jpg", mRgba); and in general it saves more that I want to. I want to save image without rectangle Imgproc.rectangle(mRgba, new Point(touchedYD, touchedXL), new Point(touchedYU, touchedXR), Util.WHITE, 2); that is drawn on screen before saving. How to achieve that?
Here is my code.
Fragment:
public class StageTwo extends Fragment implements CameraBridgeViewBase.CvCameraViewListener2, OnSwitchFragmentFromStageTwo {
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((Stages) getActivity()).onSwitchFragmentFromStageTwo = this;
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// poziomo
if (-event.getX() + camLayHeight + (xCorrection * 10) < (camLayHeight / 2)) {
touchedXR = -event.getX() + camLayHeight + (xCorrection * 10);
if (touchedXR < 0) touchedXR = 0;
} else {
touchedXL = -event.getX() + camLayHeight + (xCorrection * 10);
if (touchedXL > camLayHeight) touchedXL = camLayHeight;
}
// pionowo
if (event.getY() - (yCorrection * 10) < (camLayWidth / 2)) {
touchedYU = event.getY() - (yCorrection * 10);
if (touchedYU < 0) touchedYU = 0;
} else {
touchedYD = event.getY() - (yCorrection * 10);
if (touchedYD > camLayWidth) touchedYD = camLayWidth;
}
return true;
}
});
kamera = view.findViewById(R.id.java_surface_view);
kamera.setCvCameraViewListener(this);
Display display = getActivity().getWindowManager().getDefaultDisplay();
android.graphics.Point size = new android.graphics.Point();
display.getSize(size);
int height = size.y;
kamera.getLayoutParams().height = height / 2;
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Core.transpose(mGray, mGray);
Core.flip(mGray, mGray, -1);
Imgproc.cvtColor(inputFrame.rgba(), mRgba, Imgproc.COLOR_RGBA2RGB, 1);
if (gridPref.equals(getString(R.string.yes))) {
Imgproc.line(mRgba, p1, p2, Util.BLUE);
Imgproc.line(mRgba, p3, p4, Util.BLUE);
}
Imgproc.rectangle(mRgba, new Point(touchedYD, touchedXL), new Point(touchedYU, touchedXR), Util.WHITE, 2);
rozmiar_y = (int) ((touchedYU - touchedYD));
rozmiar_x = (int) ((touchedXL - touchedXR));
if (rozmiar_x > rozmiar_y)
px_cm = (double) Math.round((rozmiar_x / Integer.parseInt(rozmiar)) * 100000) / 100000d;
if (rozmiar_x < rozmiar_y)
px_cm = (double) Math.round((rozmiar_y / Integer.parseInt(rozmiar)) * 100000) / 100000d;
return mRgba;
}
#Override
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC3);
new Mat(height, width, CvType.CV_8UC4);
mGray = new Mat(height, width, CvType.CV_8UC1);
camLayHeight = height; // mniejsza wartosc 480
camLayWidth = width;
touchedXL = camLayHeight / 2;
touchedXR = camLayHeight / 2;
touchedYD = camLayWidth / 2;
touchedYU = camLayWidth / 2;
}
#Override
public void onCameraViewStopped() {
}
#Override
public double onSwitchFragmentFromFragmentTwo() {
if (px_cm > 0.5) {
(...)
Imgcodecs.imwrite(Environment.getExternalStorageDirectory() + "/final-image.jpg", mRgba);
}
return px_cm;
}
}
Activity
OnSwitchFragmentFromStageTwo onSwitchFragmentFromStageTwo;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stages);
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setItemIconTintList(null);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Stages.this);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (!sp.getBoolean("correctionDone", false))
ft.replace(R.id.content_frame, new StageZero(this));
else {
ft.replace(R.id.content_frame, new StageOne());
bottomNavigationView.setSelectedItemId(R.id.navigation_stage_one);
}
ft.commit();
SharedPreferences.Editor editor = sp.edit();
bottomNavigationView.setEnabled(false);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
(...)
if (bottomNavigationView.getSelectedItemId() == R.id.navigation_stage_two) {
if (onSwitchFragmentFromStageTwo.onSwitchFragmentFromFragmentTwo() <= 0.5) {
(...)
return false;
} else {
(...)
return true;
}
} else {
(...)
}
return true;
}
});
}
I was trying to solve this problem by setting touchedXL = 0; touchedXR = 0; touchedYD = 0; touchedYU = 0; right before saving but it did not help, picture is still saved with this rectangle. If you need something more just ask. Thank you in advance! :)
You may create a copy of mRgba before drawing the rectangle.
Add a new private class member mRgbNoRect:
private Mat mRgbNoRect; //mRgba before drawing rectangle
Initialize mRgbNoRect in onCameraViewStarted:
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC3);
mRgbNoRect = new Mat(height, width, CvType.CV_8UC3);
}
Create a copy of mRgba before drawing the rectangle in onCameraFrame:
Imgproc.cvtColor(inputFrameRgba, mRgba, Imgproc.COLOR_RGBA2RGB);
mRgba.copyTo(mRgbNoRect); //Copy mRgba content to mRgbNoRect before drawing a rectangle
Imgproc.rectangle(mRgba, new Point(20, 20), new Point(100, 100), new Scalar(255, 255, 255), 2);
Note: It's just an example (not your original code).
Add a "get" function getRgbNoRect():
public Mat getRgbNoRect() {
return mRgbNoRect;
}
Get mRgbNoRect and save it (example):
Mat rgbNoRect = sample.getRgbNoRect();
Imgcodecs.imwrite("rgbNoRect.png", rgbNoRect);
Here is a complete code sample (simple sample without a camera):
package myproject;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;
import org.opencv.core.Point;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;
class Sample {
private Mat mRgba;
private Mat mRgbNoRect; //mRgba before drawing rectangle
static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public Mat onCameraFrame() {
//Create RGBA matrix filled with grin color - simulating inputFrame.rgba().
Mat inputFrameRgba = Mat.zeros(200, 250, CvType.CV_8UC4);
inputFrameRgba.setTo(new Scalar(0, 255, 0, 255));
Imgproc.cvtColor(inputFrameRgba, mRgba, Imgproc.COLOR_RGBA2RGB);
mRgba.copyTo(mRgbNoRect); //Copy mRgba content to mRgbNoRect before drawing a rectangle
Imgproc.rectangle(mRgba, new Point(20, 20), new Point(100, 100), new Scalar(255, 255, 255), 2);
return mRgba;
}
public Mat getRgbNoRect() {
return mRgbNoRect;
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC3);
mRgbNoRect = new Mat(height, width, CvType.CV_8UC3);
}
public static void main(String[] args) {
Sample sample = new Sample();
sample.onCameraViewStarted(250, 200);
Mat rgbWithRect = sample.onCameraFrame();
Mat rgbNoRect = sample.getRgbNoRect();
Imgcodecs.imwrite("rgbWithRect.png", rgbWithRect);
Imgcodecs.imwrite("rgbNoRect.png", rgbNoRect);
}
}
Notes:
The code sample is tested in Windows, and I am not sure if it can be executed in Android as is.
The last time I programmed in JAVA was many years ago, so I hope I didn't do some rookie's mistakes.

Text filling up from left to right

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

Polygon movement towards a point

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.

When using the button, my program closes, libgdx

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‌​)

Android AndEngine : sprite.detachSelf() doesnt remove the sprite

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).

Categories

Resources