How To Become A Programmer Without A Degree & Experience

Catch the Ball – Android Studio Game Tutorial –

[Game1] Android Studio Game Tutorial – #1 Introduction

 

 
 

 
 

Introduction & Demo

Welcome to my first Android Studio Game Tutorial!
I’m so glad that you get interested in this tutorial 🙂

In this tutorial, we’ll create the game app exactly like this. (You can download free demo app from Google Play.)

If you get errors or weird situations, please leave a comment on YouTube to be able to share with everyone.

Hope you enjoy!

 
 

Start Coding & Downloads

 

 
 

Environment

Catch the Ball

Android Studio 2.1.1   (Has been tested with 3.1.2)
Emulator Genymotion (Nexus4)

Bonus

Android Studio 2.3.1   (Has been tested with 3.1.2)
Emulator Genymotion (Nexus4)

 
 

Menu

1. Introduction
2. Create a Project & Main Layout
3. FindViewById & onTouchEvent
4. Move the Box Up and Down
5. Set the Balls
6. Check Hits & Add Points
7. Result View & Save High Score
8. Start View & KeyEvent
9. Add Sound Effects
10. Optimize for Multiple Devices
11. Implement AdMob Interstitial Ad

Bonus

#1 Move Images Vertically and Horizontally
#2 Add Pause Button

 
 

  • hafsa danguir

    Best tutorial ever ! Thank you so much

    • sara

      Hi hafsa, Thanks for your comment! I’m so glad to hear that:)

      • Hafsa Danguir

        Welcome sara ! Keep up with you’re tutorial 🙂

  • https://www.facebook.com/sani.shahabuddin Sani

    😀
    <3
    ^_^

  • vaisanen

    Anyway to make the ball speed up to increase the difficulty. say after you hit 300 points it gets faster ?

    • Sara

      I left a comment on YouTube about this topic. (#11. Implement AdMob Interstitial Ad)
      ( I hope you’re the same vaisanen on YouTube! )

      • vaisanen

        Sara ! Yes I saw the comments. Sorry I thought I replied. That worked fantastic ! Thank you so much. I appreciate your response. 🙂

  • rr raymundo

    Hello, I would like to ask if it is possible to have levels on your game? For example, when the player reached 100pts, he will go to Level 2 and the speed of the distribution of the ball will get fast. I hope you notice this 🙂 Thank you!

    • Sara

      Hi rr raymundo, Thanks for watching my videos!

      Here is an example.
      if ( score < 100 ) {
      // level 1
      orangeSpeed = 12;

      } else if (100 <= score && score < 200) {
      // Level 2
      orangeSpeed = 17;

      } else if…

      You can write them inside a changePos function, but it seems a waste of memory to check the score every time.
      I recommend creating a changeSpeed function and calling it when the score changes.
      About the level, how about creating a text view next to the score label and updating it when the speed changes?
      I think it's the easiest way so that you don't need to pause the game.
      Hope this helps 🙂

  • Komik Montajlar

    İ like it very nice subject

    • Sara

      Hi Komik, Thanks!

  • chanki bhakuni

    Hey Sara. I am following this tutorial an trying to make a small game. In that game balls are going from top to bottom(Y += 10). I have set them off screen as you have shown. But the problem is that every time the game starts all the balls come together in the screen although I have set different Y position. And also they are having same X position. Once they reaches to the bottom they are coming normally(following that Math.random code) . Attaching a Screenshot. Thank You. https://uploads.disquscdn.com/images/ea3f4b4c453f1903779d5ceec02020eb354e5dd782fb35207d5fa27117230d2b.jpg

    • Sara

      Hi chanki, Can you upload a screenshot or code of changePos function?

      • chanki bhakuni
        • Sara

          I guess this is the cause… I attached the example of the red ball.
          Sorry for my handwriting! It’s easy to explain. Hope this helps 🙂
          https://uploads.disquscdn.com/images/8244e99b264d4964c81652677fbda83c2478500c049cb8a1592ccc6dc327d6dd.jpg

          • chanki bhakuni

            Thanks for the early reply. I have already tried this and this too doesn’t work. Nothing is working in this case. I had set different Y positions too but at first all balls are coming together(overlapped).
            And your handwriting is beautiful just like you. 🙂

          • Sara

            It’s weird…Does the timer start after you get the frameWidth? You need to set frameWidth before the game starts.
            If you write them in the right order, what happens if you change frameWidth to screenWidth?
            rballX = (int)Math.floor(Math.random()*screenWidth); ←here

          • chanki bhakuni

            No. Nothing is helping. Yes timer starts after getting frameWIdth

            if(start == false){

            public boolean onTouchEvent(MotionEvent me){

            if(start == false){

            start = true;

            FrameLayout frame = (FrameLayout) findViewById(R.id.framo);
            frameHeight = frame.getHeight();
            frameWidth = frame.getWidth();

            bucketX = (int)bucket.getX();
            bucketSize = bucket.getWidth();

            startLabel.setVisibility(View.GONE);

            timer.schedule(new TimerTask() {
            @Override
            public void run() {
            handler.post(new Runnable() {
            @Override
            public void run() {

            changePos();
            }
            });
            }
            },0, 20);

            }else{

            if(me.getAction() == MotionEvent.ACTION_DOWN){

          • chanki bhakuni

            For now I’m thinking of using an image to hide that portion. :p

          • Sara

            Everything looks good…As you said, if balls are coming normally after reaching the bottom, it means that frameWidth is 0 when the game starts. Let’s check frameWidth by using Log!

            Try adding this code.
            Log.v(“frameWidth”, frameWidth+””);

            public void changePos() {
            if (rballY > frameHeight) {
            // here
            }
            // here
            }

            public boolean onTouchEvent(MotionEvent me) {
            frameHeight = frame.getHeight();
            // here
            }

            Before using an image to hide, let’s try a bit more 😀

          • chanki bhakuni

            Here,
            Log.v(“frameWidth”, frameWidth+””);

            it says unknown class ‘frameWIdth+’

            and here,

            frame.getHeight();

            it says cannot resolve symbol ‘frame’.

          • Sara

            Please check for misspelling in your code.
            FrameLayout frame = (FrameLayout) findViewById(R.id.framo); // framo → frame
            it says unknown class ‘frameWIdth+’ // frameWIdth → frameWidth

          • chanki bhakuni

            framo was just an id name. still i changed it. And Here,
            Log.v(“frameWidth”, frameWidth+””);

            it still says unknown class ‘frameWIdth+’ & token expected for ‘+’ && cannot resolve symbol ‘v’.

          • Sara

            It’s weird… I wish I could help you out 🙁
            You write “Log.v(“frameWidth”, frameWidth+””);” inside methods (where I wrote “// here” before), right?

          • chanki bhakuni

            Oh sorry!! I didn’t write it there. I write it just like you did in that comment. I’ll correct it and will let you know. Thanks. And by these tutorials you have helped a lot.

          • chanki bhakuni

            This is the result

            V/frameWidth: 1440
            V/frameWidth: 1440
            V/frameWidth: 1440
            V/frameWidth: 1440
            V/frameWidth: 1440
            V/frameWidth: 1440
            V/frameWidth: 1440
            V/frameWidth: 1440
            I/System.out: collision
            V/frameWidth: 1440
            I/System.out: collision
            V/frameWidth: 1440

          • Sara

            frameWidth is set correctly (1440), and I guess frameHeight is 2560.
            When the game starts, y-coordinates of balls should be greater than 2560. Is this part okay?
            Like this: gball.setY(3000);
            I recommend checking each value using Log. It’s kind of boring, but this is how I solve problems every time 🙂

          • chanki bhakuni

            y-cordinates of balls is 5000. I also tried with (screenHeight + 1000) but nothing changed.

            Well Log is new to me but i think it is useful to know what is actually happening. Will learn how to use it.

          • Sara

            Although I checked your code once again, everything looks fine… ;(
            Don’t you set ball’s position in the XML file?
            Here is the example. If you set something like margin-top or gravity, try removing it.

          • chanki bhakuni

            No, I knew as it has to go to off screen no need to give it a particular place. I tried to write it all over again still getting same problem.

          • Sara

            I wonder why… Sorry, I wish I could help you 🙁
            If you’d like, send me your code. I’m not sure what I can do, but I’ll check it.
            (You may don’t want to upload here, so send me via email. codingwithsara@gmail.com)
            Good luck 🙂

          • chanki bhakuni

            Thanks Sara for being so helpful. I have mailed you the code.

  • Minkhun Horvejkul ♓️

    hi sara, what if i change the speed of the balls every 1 min? what should i change??

    • Sara

      +Minkhun There are two ways.
      A. Create a new timer and change speed every minute.
      B. Use the existing timer. Prepare an int variable to count time, then count inside changePos() function. (Be careful! The timer will be called every 20 milliseconds. )
      Hope this helps 🙂

  • Jerome Quitola

    hi sara :D, can u help me to put lives specially when the score is getting high & kindly put the code needed tnx 😀 tnx & i hope for ur response

    • Sara

      +Jerome I replied on YouTube, but just in case…

      private int life = 3;

      // Inside hitCheck function.
      if ( // Black hits) {
      if (score > 300) {
      life -= 1;
      }
      if (life == 0 || score <= 300) {
      // Game Over
      }
      }

      • Jerome Quitola

        im having a hard time with it , pls help me with the specific code pls , i need it in my project , TNX 😀

        • Jerome Quitola

          sorry for bothering you , it will be a great pleasure if you help me with it ^^

          • Sara

            Sorry, I can’t write entire code for your project.
            I added comments, so please try this first.

            // After “private boolean start_flg = false;”
            private int life = 3;

            // Change the part of Black in hitCheck function.
            // Black
            int blackCenterX = blackX + black.getWidth() / 2;
            int blackCenterY = blackY + black.getHeight() / 2;
            if (0 <= blackCenterX && blackCenterX <= boxSize &&
             boxY <= blackCenterY && blackCenterY 300) {
 life -= 1;
 }
if (life == 0 || score <= 300) {
               // Stop timer.
               timer.cancel();
               timer = null;
               sound.playOverSound();

               // Show Result
               Intent intent = new Intent(getApplicationContext(), result.class);
               intent.putExtra("SCORE", score);
               startActivity(intent);

              }
            
}

  • Liam

    hi Sara, I have checked my code numerous times and cant seem to find out why my box does not hit off the top and bottom of my page, it just goes off the screen until i hold the screen for it to go up.

    • Sara

      Hi Liam,
      Inequality signs ( > and < ) are correct, aren't they? I guess boxY is the cause…
      Please try checking the value of boxY by using Log.

      if (boxY frameHeight – boxSize) boxY = frameHeight – boxSize;

  • Jurj Sergiu

    hi sara, i’ve copied your code, the files, and evething, i hope i didn’t miss something. so when the box hit black ball the game stops on my emulater :(, can you give some advice?: D

    • Sara

      Hi Jurj,
      Did you get an error message or log?

      To check when the crash occurs, you can use breakpoints or comment out everything
      from
      TextView scoreLabel = (TextView) findViewById(R.id.scoreLabel);
      to
      highScoreLabel.setText(“High Score : ” + highScore);
      }

      Then, investigate line by line.
      Hope this helps 🙂

  • Rohal Kurup

    Hi Sara, thank you for the free course

    • Sara

      Hi Rohal, You’re welcome. Thanks for your comment 🙂

  • Eren Batu

    Your download link for the pictures and sound effects dont work…
    help please

    • Sara

      Hi Eren,
      I’m sorry for the late reply and any confusion.
      You need to sign up to Thinkific to download images, sounds, and sample code. (The registration is completely free.)
      Thank you for your interest in my tutorial 🙂

  • Greenrider32

    I have changed it so the Square is moving along the bottom and the balls are coming down from the top, everything is working fine apart from the hit checked
    im and not sure what the code should be. This is my current code for one of them.
    if (0 <= yellowCenterX && yellowCenterX <= boxSizeX &&
    boxY <= yellowCenterY && yellowCenterY <= boxY + boxSizeY) {

    • Sara

      Hi Greenrider32,
      Your code looks fine. Please check the LogCat output. You’ll be able to find out when and why the app crushes.

      • Greenrider32

        it doesn’t crash it just doesn’t say that it has hit one of the objects. (it doesn’t die and add any points) Which is leading me believe i have not got the right code
        Thanks for the speedy reply.
        Sorry if i am confusing you.

        • Sara

          Sorry, I misunderstood 🙁

          When yellow hits box, coordinates will be like this.
          boxX ≦ yellowX ≦ boxX + boxSize
          boxY ≦ yellowY ≦ boxY + boxSize

          So, I guess your code should be like this.
          if (boxX <= yellowX && yellowX <= boxX+boxSize && boxY <= yellowY && yellowY <= boxY+boxSize) {}

          Hope this works 🙂

  • Daniel Charles-Iyoha

    Dear Sarah thank you for the course , I would like to know how to add gems that help resurrect a user after failing like those in endless running games thanks

  • Edani

    Hi Sara Thanks alot ! i was wondering if its posable to make the box be in the middle of the screen instad of the most left ? what should be the Hit if? it dosnt recconzie my box in the middle of the screen thanks again 🙂

    • Sara

      Create boxX variable just like boxY, then change HitCheck function like this.

      Example: orange
      // boxX <= orangeCenterX <= boxX + boxSize
      // boxY <= orangeCenterY <= boxY + boxSize
      if (boxX <= orangeCenterX && orangeCenterX <= boxX + boxSize &&
      boxY <= orangeCenterY && orangeCenterY <= boxY + boxSize) {

      Hope this helps 🙂

      • Edani

        Awesome that helped alot! thought the boxX is allways 0 for me for some resson even when i did if(charaX1>screenwidth/2) charaX1=(float)screenwidth/2;
        charcter.setX(charaX1);
        and the image just magneted to the left :s Thanks again!

        • Sara

          Yay! Glad you solved it 🙂

  • Rizaly Castrudes Beniga

    hi sara, can i follow your codes without using Android Studio? I’m using cmd though, i dont have a nice processor but i want to learn, i wonder if your code will okay without using Android Studio 🙁

    • Sara

      Hi Rizaly, I’m not sure about it… I heard it worked with Eclipse, but I’ve only tested with Android Studio. I’m sorry I couldn’t be of any help. And, thank you so much for finding my video 🙂

      • Rizaly Castrudes Beniga

        It actually worked 🙂 Thank you so much Sara <3

        • Sara

          Glad it worked! Thanks for letting me know 🙂

  • Ranjeet Kumar

    Hi Sara Thanks alot ! i was wondering if its posable to make the box in HorizontalScrollView ? what should be the Hit code ? please help me. Thanks again