How To Add Android Studio Game Sound Effect Hit Sound, Touch Sound - java

Bro How To Add Hit Sound Touch Sound Give ME Full Code.I Do't Undestand
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SoundPlayer sound;
MediaPlayer player;
List item
private GameView gameView;
private final Handler handler = new Handler();
private final static long Interval = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.bg_music);
mediaPlayer.setLooping(true);
mediaPlayer.start();
gameView = new GameView(this);
setContentView(gameView);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(() -> gameView.invalidate());
}
},0,Interval);
}
#Override
protected void onResume() {
super.onResume();
mediaPlayer.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
}
My Game View Class Code
List item
public class GameView extends View {
private SoundPlayer soundPlayer;
MediaPlayer player;
private final Bitmap[] mouse = new Bitmap[2];
private Bitmap orange;
private Bitmap malone;
private Bitmap grapes;
private Bitmap cat;
private Bitmap cat2;
private final int mouseX = 50;
private int mouseY;
private int mouseSpeed;
private int orangeX;``
private int orangeY;
private int maloneX;
private int maloneY;
private int grapesX;
private int grapesY;
private int catX;
private int catY;
private int cat2X;
private int cat2Y;
private int score,lifeCounterOfCat;
private final Paint scorePaint = new Paint();
private boolean touch = false;
private Bitmap backgroundImage;
private final Bitmap[] life = new Bitmap[2];
public GameView(Context context) {
super(context);
mouse[0] = BitmapFactory.decodeResource(getResources(), R.drawable.mouse);
mouse[0] = Bitmap.createScaledBitmap(mouse[0], 200, 200, true);
mouse[1] = BitmapFactory.decodeResource(getResources(), R.drawable.mouse2);
backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
backgroundImage = Bitmap.createScaledBitmap(backgroundImage, (int) (backgroundImage.getWidth() * 0.6), (int) (backgroundImage.getHeight() * 0.6), true);
scorePaint.setColor(Color.WHITE);
scorePaint.setTextSize(70);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
orange = BitmapFactory.decodeResource(getResources(), R.drawable.orange);
orange = Bitmap.createScaledBitmap(orange, 150, 150, true);
malone = BitmapFactory.decodeResource(getResources(), R.drawable.melone);
malone = Bitmap.createScaledBitmap(malone, 150, 150, true);
grapes = BitmapFactory.decodeResource(getResources(), R.drawable.grapes);
grapes = Bitmap.createScaledBitmap(grapes, 190, 190, true);
cat = BitmapFactory.decodeResource(getResources(), R.drawable.cat);
cat = Bitmap.createScaledBitmap(cat, 500, 400, true);
cat2 = BitmapFactory.decodeResource(getResources(), R.drawable.cat2);
cat2= Bitmap.createScaledBitmap(cat, 500, 400, true);
life[0] = BitmapFactory.decodeResource(getResources(), R.drawable.life);
life[0] = Bitmap.createScaledBitmap(life[0], 140, 140, true);
life[1] = BitmapFactory.decodeResource(getResources(), R.drawable.life_down);
life[1] = Bitmap.createScaledBitmap(life[1], 140, 140, true);
mouseY = 800;
score = 0;
lifeCounterOfCat = 4;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int canvasWidth = getWidth();
int canvasHeight = getHeight();
canvas.drawBitmap(backgroundImage,0,0,null);
int minMouseY = mouse[0].getHeight();
int maxMouseY= canvasHeight - mouse[0].getHeight();
mouseY = mouseY + mouseSpeed;
if (mouseY <minMouseY)
{
mouseY = minMouseY;
}
if (mouseY >maxMouseY)
{
mouseY =maxMouseY;
}
mouseSpeed = mouseSpeed + 3;
if (touch)
{
canvas.drawBitmap(mouse[1],mouseX,mouseY,null);
touch = false;
}
else
{
canvas.drawBitmap(mouse[0],mouseX,mouseY,null);
}
int orangeSpeed = 3;
orangeX = orangeX - orangeSpeed;
if (hitBallChecker(orangeX , orangeY))
{
score = score + 10;
orangeX = - 100;
}
orangeX = orangeX- orangeSpeed;
if (orangeX<0)
{
orangeX = canvasWidth + 21;
orangeY = (int) Math.floor(Math.random() * (maxMouseY - minMouseY)) + minMouseY;
}
int maloneSpeed = 6;
maloneX = maloneX - maloneSpeed;
if (hitBallChecker(maloneX , maloneY))
{
score = score + 25;
maloneX= -100;
}
maloneX = maloneX- maloneSpeed;
if (maloneX < 0)
{
maloneX = canvasWidth + 21;
maloneY = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
int grapesSpeed = 5;
grapesX = grapesX - grapesSpeed;
if (hitBallChecker(grapesX , grapesY))
{
score = score + 35;
grapesX = -120;
}
grapesX = grapesX- grapesSpeed;
if (grapesX < 0)
{
grapesX = canvasWidth + 21;
grapesY = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
int catSpeed = 8;
catX = catX - catSpeed;
hitBallChecker(catX, catY);
int cat2Speed = 5;
cat2X = cat2X - cat2Speed;
if (hitBallChecker(cat2X , cat2Y)) {
catX = -800;
lifeCounterOfCat--;
cat2X = -500;
lifeCounterOfCat--;
if (lifeCounterOfCat == 0)
{
Toast.makeText(getContext(), "Game Over", Toast.LENGTH_SHORT).show();
Intent gameOverIntent = new Intent(getContext(), GameOver.class);
gameOverIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
getContext().startActivity(gameOverIntent);
}
}
catX = catX- catSpeed;
if (catX < 0)
{
catX = canvasWidth + 500;
catY = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
cat2X = cat2X- cat2Speed;
if (cat2X < 0)
{
cat2X = canvasWidth + 400;
cat2Y = (int) Math.floor(Math.random()* (maxMouseY - minMouseY)) + minMouseY;
}
canvas.drawText("score :" + score, 20,60, scorePaint);
//Life Counter//
for (int i=0; i<3; i++)
{
int x = (int) (700 + life[0]. getWidth() * 0.8* i);
int y = 30;
if (i < lifeCounterOfCat)
{
canvas.drawBitmap(life[0],x,y,null);
}
else
{
canvas.drawBitmap(life[1],x,y,null);
}
}
canvas.drawBitmap(orange,orangeX,orangeY,null);
canvas.drawBitmap(malone, maloneX,maloneY,null);
canvas.drawBitmap(grapes,grapesX,grapesY,null);
canvas.drawBitmap(cat,catX,catY,null);
canvas.drawBitmap(cat2,cat2X,cat2Y,null);
}
public boolean hitBallChecker(int x, int y)
{
return mouseX < x && x < (mouseX + mouse[0].getWidth()) && mouseY < y && y < (mouseY + mouse[0].getHeight());
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouchEvent(MotionEvent event)
{
event.getAction();
{
touch = false;
mouseSpeed = - 22;
}
return true;
}
}

Related

How do I make multiple balls drop from the top?

public class MovingBagView extends View {
private Bitmap bag[] = new Bitmap[2];
private int bagX;
private int bagY = 1000;
private int bagSpeed;
private Boolean touch = false;
private int canvasWidth, canvasHeight;
private int yellowX = 500, yellowY, yellowSpeed = -16;
private Paint yellowPaint = new Paint();
private int score;
private Bitmap backgroundImage;
private Paint scorePaint = new Paint();
private Bitmap life[] = new Bitmap[2];
public MovingBagView(Context context) {
super(context);
bag[0] = BitmapFactory.decodeResource(getResources(), R.drawable.bag1);
bag[1] = BitmapFactory.decodeResource(getResources(), R.drawable.bag2);
backgroundImage = BitmapFactory.decodeResource(getResources(), R.drawable.background);
yellowPaint.setColor(Color.YELLOW);
yellowPaint.setAntiAlias(false);
scorePaint.setColor(Color.BLACK);
scorePaint.setTextSize(40);
scorePaint.setTypeface(Typeface.DEFAULT_BOLD);
scorePaint.setAntiAlias(true);
life[0] = BitmapFactory.decodeResource(getResources(), R.drawable.heart);
life[1] = BitmapFactory.decodeResource(getResources(), R.drawable.heart_grey);
bagX = 10;
score = 0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvasWidth = canvas.getWidth();
canvasHeight = canvas.getHeight();
canvas.drawBitmap(backgroundImage, 0, 0, null);
int minBagX = bag[0].getWidth();
int maxBagX = canvasWidth - bag[0].getWidth() * 2;
bagX = bagX + bagSpeed;
if (bagX < minBagX) {
bagX = minBagX;
}
if (bagX >= maxBagX) {
bagX = maxBagX;
}
bagSpeed = bagSpeed + 2;
if (touch) {
canvas.drawBitmap(bag[1], bagX, bagY, null);
}
else {
canvas.drawBitmap(bag[0], bagX, bagY, null);
}
yellowY = yellowY - yellowSpeed;
if (hitBallChecker(yellowX, yellowY)) {
score = score + 10;
yellowY = -100;
}
if (yellowY < 0) {
yellowY = canvasHeight + 21;
yellowX = (int)Math.floor(Math.random() * (maxBagX - minBagX)) + maxBagX;
}
canvas.drawCircle(yellowX, yellowY, 15, yellowPaint);
canvas.drawText("Score : " + score, 20, 60, scorePaint);
canvas.drawBitmap(life[0], 500, 10, null);
canvas.drawBitmap(life[0], 570, 10, null);
canvas.drawBitmap(life[0], 640, 10, null);
}
public boolean hitBallChecker(int x, int y) {
if (bagY < y && y < (bagY + bag[0].getHeight()) && bagX < x && x < (bagX + bag[0].getWidth())) {
return true;
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touch = true;
bagSpeed = -22;
}
return true;
}
}
I've figured out how to make the balls drop from the top of the screen. The code is supposed to make multiple yellow balls drop from the top of the screen, but only one yellow ball drops. Random yellow balls are supposed to drop from the top, and they drop from different positions. You can see the preview of it below:
To implement this, you should consider creating a custom object Ball
public class Ball{
public int x;
public int y;
public int speed;
public Ball(int x, int y, int speed){
this.x = x;
this.y = y;
this.speed = speed;
}
}
Then you can add multiple Balls in an ArrayList and in the draw() you iterate through every Ball in the array and do what you've been doing to one Ball with each.
for(int i = 0; i < balls.length(); i++){
Ball ball = balls.get(i);
ball.y -= ball.speed;
// check for collisions
// draw ball
}

Android Canvas Animation Appears to Stutter (Not Smooth)

I am making an app where balls fall from the top of the screen to the bottom of the screen, and the user has to touch a certain area to make the balls disappear. However, when the balls fall, they appear to stutter as the fall down the screen. Here is the entire code for the project:
public class GameActivity extends Activity implements View.OnTouchListener {
MyBringBack ourSurfaceView;
Paint p;
float x, y, secondX, secondY;
int firstRun;
Bitmap green, red, blue, purple, white;
int currentColor;
ArrayList<Ball> balls = new ArrayList<>();
Paint buttonPaint;
Boolean thingFirstRun;
int score;
Model model;
int cHeight, cWidth;
int nextBallSpeed;
int totalBalls;
int countBalls;
int buttonState = 0;
public final static int BUTTON_NONE = 0;
public final static int BUTTON_LEFT = 1;
public final static int BUTTON_RIGHT = 2;
public final static int BUTTON_BOTH = 3;
class Ball {
public Ball(int x, int y, int s, int color, Bitmap b) {
xCord = x;
yCord = y;
speed = s;
this.color = color;
passedLineYet = false;
bitmap = b;
}
public int xCord;
public int yCord;
public int speed;
public int color;
public boolean passedLineYet;
public Bitmap bitmap;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
red = BitmapFactory.decodeResource(getResources(), R.drawable.redcircle);
blue = BitmapFactory.decodeResource(getResources(), R.drawable.bluecircle);
green = BitmapFactory.decodeResource(getResources(), R.drawable.greencircle);
purple = BitmapFactory.decodeResource(getResources(), R.drawable.purplecircle);
white = BitmapFactory.decodeResource(getResources(), R.drawable.white);
secondX = secondY = -1;
cHeight = 0;
cWidth = 0;
countBalls = 0;
nextBallSpeed = 60;
p = new Paint();
p.setColor(Color.WHITE);
p.setTextSize(200);
ourSurfaceView = new MyBringBack(this);
ourSurfaceView.setOnTouchListener(this);
setContentView(ourSurfaceView);
model = new Model();
score = 0;
(new Thread(model)).start();
thingFirstRun = false;
currentColor = Color.GREEN;
buttonPaint = new Paint();
buttonPaint.setColor(currentColor);
buttonPaint.setStrokeWidth(10);
buttonPaint.setStyle(Paint.Style.FILL);
firstRun = 0;
}
public boolean correctColor(Ball b) {
if (currentColor == b.color) {
return true;
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
#Override
protected void onPause() {
super.onPause();
ourSurfaceView.pause();
}
#Override
protected void onResume() {
super.onResume();
ourSurfaceView.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event) {
try {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
float xEvent = event.getX(event.getPointerId(event.getActionIndex()));
float yEvent = event.getY(event.getPointerId(event.getActionIndex()));
if (yEvent > cHeight / 4 * 3) {
if (xEvent < cWidth / 2) {
buttonState |= BUTTON_LEFT;
}
if (xEvent > cWidth / 2) {
buttonState |= BUTTON_RIGHT;
}
}
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
try {
xEvent = event.getX(event.getPointerId(event.getActionIndex()));
yEvent = event.getY(event.getPointerId(event.getActionIndex()));
} catch (Exception e) {
xEvent = event.getX();
yEvent = event.getY();
}
if (yEvent > cHeight / 4 * 3) {
if (xEvent < cWidth / 2) {
buttonState &= ~BUTTON_LEFT;
}
if (xEvent > cWidth / 2) {
buttonState &= ~BUTTON_RIGHT;
}
}
break;
}
switch (buttonState) {
case BUTTON_LEFT:
currentColor = Color.RED;
break;
case BUTTON_RIGHT:
currentColor = Color.BLUE;
break;
case BUTTON_BOTH:
currentColor = Color.MAGENTA;
break;
case BUTTON_NONE:
currentColor = Color.GREEN;
break;
}
buttonPaint.setColor(currentColor);
Log.v("BUTTON STATE", buttonState + "");
Log.v("BUTTON COLOR", currentColor + "");
return true;
} catch (Exception e) {
}
return true;
}
public class Model extends Thread implements Runnable {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000 / 240);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (countBalls % nextBallSpeed == 0) {
int temp = (int) (Math.random() * 4);
if (temp == 0) {
balls.add(new Ball((int) (Math.random() * (cWidth - red.getWidth())), 0 - red.getHeight(), cHeight / 800, Color.RED, red));
} else if (temp == 1) {
balls.add(new Ball((int) (Math.random() * (cWidth - red.getWidth())), 0 - green.getHeight(), cHeight / 800, Color.GREEN, green));
} else if (temp == 2) {
balls.add(new Ball((int) (Math.random() * (cWidth - blue.getWidth())), 0 - blue.getHeight(), cHeight / 800, Color.BLUE, blue));
} else if (temp == 3) {
balls.add(new Ball((int) (Math.random() * (cWidth - purple.getWidth())), 0 - purple.getHeight(), cHeight / 800, Color.MAGENTA, purple));
}
totalBalls++;
}
if (totalBalls < 10) {
nextBallSpeed = 30;
} else if (totalBalls < 30) {
nextBallSpeed = 25;
} else if (totalBalls < 50) {
nextBallSpeed = 20;
} else if (totalBalls < 80) {
nextBallSpeed = 15;
} else if (totalBalls < 150) {
nextBallSpeed = 10;
} else {
nextBallSpeed = 5;
}
for (int i = 0; i < balls.size(); i++) {
int h = cHeight;
balls.get(i).yCord += balls.get(i).speed;
}
for (int i = 0; i < balls.size(); i++) {
try {
if (balls.get(i).yCord + green.getHeight() > ((double) cHeight * .75) && !balls.get(i).passedLineYet) {
balls.get(i).passedLineYet = true;
boolean b = correctColor(balls.get(i));
if (b) {
balls.remove(i);
score++;
}
if (!b) {
}
} else if (balls.get(i).yCord > cHeight) {
balls.remove(i);
score -= 5;
}
} catch (Exception ignored) {
}
}
countBalls++;
}
}
public boolean correctColor(Ball b) {
if (currentColor == b.color) {
return true;
}
return false;
}
}
public class MyBringBack extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public MyBringBack(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
#Override
public void run() {
while (isRunning) {
try {
Thread.sleep(1000 / 240);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!ourHolder.getSurface().isValid()) {
continue;
}
//NE
Bitmap tempCanvasBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas tempCanvas = new Canvas();
tempCanvas.setBitmap(tempCanvasBitmap);
//NEND
//Canvas canvas = ourHolder.lockCanvas();
tempCanvas.drawColor(Color.BLACK);
if (firstRun == 0) {
cHeight = tempCanvas.getHeight();
cWidth = tempCanvas.getWidth();
red = getResizedBitmap(red, tempCanvas.getWidth() / 12, tempCanvas.getWidth() / 12);
green = getResizedBitmap(green, tempCanvas.getWidth() / 12, tempCanvas.getWidth() / 12);
blue = getResizedBitmap(blue, tempCanvas.getWidth() / 12, tempCanvas.getWidth() / 12);
purple = getResizedBitmap(purple, tempCanvas.getWidth() / 12, tempCanvas.getWidth() / 12);
white = getResizedBitmap(white, cHeight / 4 * 3, cWidth / 20);
firstRun = 1;
totalBalls = 0;
}
//canvas.drawBitmap(white, );
tempCanvas.drawRect(0, tempCanvas.getHeight() * 3 / 4, tempCanvas.getWidth(), tempCanvas.getHeight(), buttonPaint);
for (int i = 0; i < balls.size(); i++) {
try {
tempCanvas.drawBitmap(balls.get(i).bitmap, balls.get(i).xCord, balls.get(i).yCord, null);
} catch (Exception ignored) {
}
}
Rect r = new Rect();
p.getTextBounds(score + "", 0, (score + "").length(), r);
tempCanvas.drawText(score + "", cWidth - r.width() - 20, r.height() + 20, p);
Canvas canvas = ourHolder.lockCanvas();
canvas.drawBitmap(tempCanvasBitmap, 0, 0, p);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
I have created animations before, but without the use of a Runnable (all code in the onDraw() method). Perhaps the issue is with that.
Does anyone know why this stuttering might be occurring?
Use This:
Add the class member fields, replace your run(), and add primeCanvas() method.
boolean isPrimed = false;
Canvas canvas;
#Override
public void run() {
while(isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
canvas = ourHolder.lockCanvas();
if(!isPrimed)
primeCanvas();
canvas.drawColor(Color.BLACK);
canvas.drawRect(0, canvas.getHeight() * 3 / 4, canvas.getWidth(), canvas.getHeight(), buttonPaint);
for(int i = 0; i < balls.size(); i ++)
canvas.drawBitmap(balls.get(i).bitmap, balls.get(i).xCord, balls.get(i).yCord, null);
Rect r = new Rect();
p.getTextBounds(score + "", 0, (score + "").length(), r);
canvas.drawText(score + "", cWidth - r.width() - 20, r.height() + 20, p);
ourHolder.unlockCanvasAndPost(canvas);
}
}
private void primeCanvas() {
cHeight = canvas.getHeight();
cWidth = canvas.getWidth();
red = getResizedBitmap(red, canvas.getWidth()/12, canvas.getWidth()/12);
green = getResizedBitmap(green, canvas.getWidth()/12, canvas.getWidth()/12);
blue = getResizedBitmap(blue, canvas.getWidth()/12, canvas.getWidth()/12);
purple = getResizedBitmap(purple, canvas.getWidth()/12, canvas.getWidth()/12);
white = getResizedBitmap(white, cHeight / 4 * 3, cWidth / 20);
firstRun = 1;
totalBalls = 0;
}

How to check if the screen has not been touched

I have a game that displays circles randomly on the screen. The circles can be green or red at random. If you touch a red circle something happens; if you touch a green circle something happens; but what if you wanted to check if the green circle was displayed and a user did not click it? Here is my code:
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
public static int savedScore;
public static List<String> a = new ArrayList<String>();
public static String[] savedScores = new String[a.size()];
Paint red;
public static int howManyPoints;
public static int highestScore = 0;
boolean isTouched;
Thread newThread = new Thread();
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
if(lastColor == greenColor){
isTouched = false;
}
if(addPoints < 10){
handler.postDelayed(this, 850);
}
if(addPoints > 9 && addPoints < 30){
handler.postDelayed(this,700);
}
if(addPoints > 29){
handler.postDelayed(this, 600);
}
if(addPoints > 50){
handler.postDelayed(this, 450);
}
if(addPoints > 100){
handler.postDelayed(this, 400);
}
postInvalidate();
}
};
public void what(){
try {
newThread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(isTouched == false){
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
Paint back = new Paint();
back.setColor(Color.BLACK);
Rect background = new Rect();
background.set(0, 0, canvas.getWidth(),canvas.getHeight() );
canvas.drawRect(background, back);
Paint newPaint = new Paint();
newPaint.setColor(Color.BLUE);
newPaint.setTextSize(60);
canvas.drawText("Beta v2", 10, 60, newPaint);
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight, radius, paint);
what();
red = new Paint();
red.setColor(Color.BLUE);
red.setTextSize(150);
canvas.drawText("" + addPoints, 500, 1350, red);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(lastColor == redColor){
//saveScore();
howManyPoints = addPoints;
if(howManyPoints > highestScore){
highestScore = howManyPoints;
}
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
if(lastColor == greenColor){
addPoints++;
isTouched = true;
}
}else {
}
}
return false;
}
public void saveScore() {
a.add("" + addPoints);
//if(Integer.parseInt(savedScores[1]) < addPoints){
//savedScores[2] = savedScores[1];
//int x = Integer.parseInt(savedScores[1]);
//x = addPoints;
//}
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}
Just add a boolean hasBeenClicked that is false and becomes true when the user touches it

My onTouch method is not doing its proper fucntion

I am making a Android app. The objective is to make circles that when touched something happens. Here is the onTouch method
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(redColor == lastColor){
Intent i = new Intent(v.getContext(), YouFailed.class);
v.getContext().startActivity(i);
} else {
addPoints++;
}
}else {
}
return true;
}
This part of the code is the thing that is not functioning properly here is the entire class below.
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
invalidate();
handler.postDelayed(this, 1000);
}
};
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight + radius/2f, radius, paint);
paint.setColor(Color.BLACK);
paint.setTextSize(150);
canvas.drawText("Score: " + addPoints, 120, 300, paint);
}
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(redColor == lastColor){
Intent i = new Intent(v.getContext(), YouFailed.class);
v.getContext().startActivity(i);
} else {
addPoints++;
}
}else {
}
return true;
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius)))
return true;
return false;
}
}

for loop does not "grow" the circle. I need to "grow" a circle

I am trying to write an android application that draws Circles at random positions over and over forever. This is already done in my code. The next objective for me is to slowly animate these circles to make them "grow" onto the screen. Basically increment the radius of the circle from 0 to 300 very fast I did this by creating a for loop like this.
for(int i = 0;i< 300; i++){
canvas.drawCircle(randomWidthOne, randomHeightOne,i, newPaint);
}
unfortunately this does not perform the desired result. Instead it just displays the circles at the end radius of 300. Here is my code for the class that draws the circles. Please let me know if there is anything in the class that is interfering with what I am trying to accomplish.
public class SplashLaunch extends View{
Handler cool = new Handler();
DrawingView v;
Paint newPaint = new Paint();
int randomWidthOne = 0;
int randomHeightOne = 0;
private float radiusNsix = 10;
private float radiusNfive = 25;
private float radiusNfour = 50;
private float radiusNthree = 100;
private float radiusNtwo = 150;
private float radiusNone = 200;
private float radiusZero = 250;
private float radiusOne = 300;
final int redColorOne = Color.RED;
final int greenColorOne = Color.GREEN;
private static int lastColorOne;
double startTime = System.currentTimeMillis();
ObjectAnimator radiusAnimator;
private final Random theRandom = new Random();
public SplashLaunch(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
private final Runnable circleUpdater = new Runnable() {
#Override
public void run() {
lastColorOne = theRandom.nextInt(2) == 1 ? redColorOne : greenColorOne;
newPaint.setColor(lastColorOne);
cool.postDelayed(this, 1000);
invalidate();
}
};
#Override
protected void onAttachedToWindow(){
super.onAttachedToWindow();
cool.post(circleUpdater);
}
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
cool.removeCallbacks(circleUpdater);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
if(theRandom == null){
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}else {
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}
for(int i = 0;i< 300; i++){
canvas.drawCircle(randomWidthOne, randomHeightOne,i, newPaint);
}
}
public void setRadiusOne(float value){
this.radiusOne = value;
invalidate();
}
public int startAnimation(int animationDuration) {
if (radiusAnimator == null || !radiusAnimator.isRunning()) {
// Define what value the radius is supposed to have at specific time values
Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
Keyframe kf2 = Keyframe.ofFloat(0.5f, 180f);
Keyframe kf1 = Keyframe.ofFloat(1f, 360f);
// If you pass in the radius, it will be calling setRadius method, so make sure you have it!!!!!
PropertyValuesHolder pvhRotation = PropertyValuesHolder.ofKeyframe("radiusOne", kf0, kf1, kf2);
radiusAnimator = ObjectAnimator.ofPropertyValuesHolder(this, pvhRotation);
radiusAnimator.setInterpolator(new LinearInterpolator());
radiusAnimator.setDuration(animationDuration);
radiusAnimator.start();
}
else {
Log.d("Circle", "I am already running!");
}
return animationDuration;
}
public void stopAnimation() {
if (radiusAnimator != null) {
radiusAnimator.cancel();
radiusAnimator = null;
}
}
public boolean getAnimationRunning() {
return radiusAnimator != null && radiusAnimator.isRunning();
}
}
Call this.invalidate() to force redraw on next frame:
private int x = -1;
private int y = -1;
private int r = -1;
private int stepsLeft = 300;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (x < 0) { // generate new circle
int[] xy = generateXY();
x = xy[0];
y = xy[1];
r = 0;
}
if (stepsLeft > 0) {
canvas.drawColor(Color.WHITE);
canvas.drawCircle(x, y, r, newPaint); // draw circle with new radius
r++; // increment radius
stepsLeft--; // decrement steps
this.invalidate(); // invalidate the view
}
}
private int[] generateXY() {
if (theRandom == null) {
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
} else {
randomWidthOne =(int) (theRandom.nextInt((int) Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}
return new int[]{randomWidthOne, randomHeightOne};
}
Have a look at the property animator.

Categories

Resources