Skip to main content
 

How to make a 2D Game in Android Studio Using Koltin


2D Game in Android Studio Using Koltin

Hello guys, There are many games in the Play Store, which are developed by the much big company. If you want to develop, that type of games, then you surely move to Unity, which is a platform to developed 3D games. But if don't want to develop 3D games, then you can try android studio to develop 2D games. I completely agree that android studio is not for game development, but if you started with game development in the android studio, it will be very easy to develop an application in the android studio. In this tutorial post, we will learn "How to make a 2D Game in Android Studio Using Koltin".We will use kotlin language for this tutorial.

Our game will look like this after development:




So, Let get started with the tutorial:


Create a new project in Android Studio

  1. Create an empty project in the android studio.
  2. Name your application.
  3. Then select the Kotlin support.
  4. After that, select the API level for your app.
  5. You want to select an empty activity for this project.
  6. Then and hit finish.


Techniques of the game

In the development of the game, we will not use a layout file. Instant of that, we will use the Surface holder and Surface view method. Basically, Surface View is a canvas, where we can draw anything, and Surface Holder is a method which holds the characters of the game. Also, we will use draw and update function to draw the characters and update the position of our characters in the game. In this game, we will display the score of the player.

The idea for this game is very simple. The player wants to cross the obstacles, to increase the score. So, let's move to our main activity. In the main activity, you want to write codes for full screen.



1
2
3
4
5
6
7
8
class MainActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(GamePanel(this))
    }
}


After that, create a new class. Name it "GamePanel".And write some codes for the Surface holder and Surface view. Here we will use five override method of the surface view. The first method is "Surface changed", which handle the position, changed of the characters. Another method is "Surface Created", which create the surface of the game. The Third method is "Surface Destroyed", which prevent the game from crashing. Our four override method is "On Touch Event", this method handles the touch inputs. After that our last method is "draw" method, which draws characters in the surface. Except for all override method, we will use a function called "update".


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class GamePanel(context: Context) : SurfaceView(context), SurfaceHolder.Callback {

    private val thread: MainThread
    
 
 
    init {
        holder.addCallback(this)

        thread = MainThread(holder, this)

        isFocusable = true

    }

 
 
    override fun surfaceChanged(holder: SurfaceHolder) {

        thread.setRunning(true)
        thread.start()
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        var retry = true
        while (retry) {
            try {
                thread.setRunning(false)
                thread.join()
            } catch (e: Exception) {
                e.printStackTrace()
            }

            retry = false
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
  
       return super.onTouchEvent(event);
        

    }

    fun update() {
       
    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)
  
    }
}

Create a new class

Now, create a new class, and give it the name "MainThread".The main thread class basically use for calling the game panel, to update the state of the game and drawing the characters of the game in the surface or canvas. Main thread class codes are as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class MainThread(private val surfaceHolder: SurfaceHolder, private val gamePanel: GamePanel) : Thread() {
    private var averageFPS: Double = 0.toDouble()
    private var running: Boolean = false

    fun setRunning(running: Boolean) {
        this.running = running
    }

    override fun run() {
        var startTime: Long
        var timeMillis = (1000 / MAX_FPS).toLong()
        var waitTime: Long
        var totalTime: Long = 0
        var frameCount = 0
        val targetTime = (1000 / MAX_FPS).toLong()

        while (running) {
            startTime = System.nanoTime()
            canvas = null

            try {
                canvas = this.surfaceHolder.lockCanvas()
                synchronized(surfaceHolder) {
                    this.gamePanel.update()
                    this.gamePanel.draw(canvas!!)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                if (canvas != null) {
                    try {
                        surfaceHolder.unlockCanvasAndPost(canvas)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                }
            }

            timeMillis = (System.nanoTime() - startTime) / 1000000
            waitTime = targetTime - timeMillis

            try {
                if (waitTime > 0)
                    sleep(waitTime)
            } catch (e: Exception) {
                e.printStackTrace()
            }

            totalTime += System.nanoTime() - startTime
            frameCount++
            if (frameCount == MAX_FPS) {
                averageFPS = (1000 / (totalTime / frameCount / 1000000)).toDouble()
                frameCount = 0
                totalTime = 0
                println(averageFPS)
            }
        }
    }

    companion object {
        val MAX_FPS = 30
        var canvas: Canvas? = null
    }
}


Solving the Errors



If you finding this type of error, then remove the line, which I was highlighted in the above picture.

Conclusion

In this article, I have created the Game loop. In the next article, I will draw the characters of games, and I will publish it soon. If you found this article helpful, then please visit again. Thank you.

Comments

Popular posts from this blog

How to Create Calculator in Android Studio Using Kotlin

Hi Friends, calculator app is very easy to create in the android studio using Kotlin language as a language. In this article, I will write " How to Create Calculator in Android Studio Using Kotlin ".In this calculator app, I will design a beautiful user interface which you can publish in the play store. Generally, people only write about the logic of the app, but here I will write logic with an elegant user interface. So, let jump into the android studio. Let get started with calculator android app: Step 1: Create a new project in the android studio. Now, give the name of the application. Make sure you check the box of Kotlin support. Step 2: Select the API Level as per your wish. Select the Empty Activity in the project, And click next. Then, click finish and your project will be loaded. Now, for designing a beautiful User Interface. We will use Linear layout in our project. In the layout, there will be seven horizontal linear layouts. A

How to make image slider by view flipper in the android studio(kotlin)

Hi Guys, you have seemed professional android application which usually having image slider, So, in this, we will learn " How to make image slider by view flipper in the android studio(kotlin) ". activity_main.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" xmlns:app= "http://schemas.android.com/apk/res-auto" android:layout_width= "match_parent" android:layout_height= "match_parent" tools:context= ".MainActivity" android:orientation= "vertical" > <ViewFlipper android:id= "@+id/v_flipper" android:layout_width= "match_parent" android:layout_height= "220dp" /> </LinearLayout> MainActivity.kt 1 2