How to make a 2D Game in Android Studio Using Koltin 003
Hi Guys, So, we have completed the "Game Loop" and we have successfully created a rectangle in our screen. Now in this article, we will describe our obstacles size, width, height, and the gap from where our player can pass. And In the next article, we will draw obstacles on the screen. If you have not read, previous articles yet, then click here. So, Let's get started with our tutorial.
Create an Object
Create an object and Name it "Constants"
In the constants object, we will store the screen height, screen width, and the context, init time of the game. Copy below codes and paste it into your constants object.
1 2 3 4 5 6 7 | object Constants { var SCREEN_WIDTH:Int = 0 var SCREEN_HEIGHT:Int = 0 var CURRENT_CONTEXT: Context? = null var INIT_TIME:Long = 0 } |
Now, describe the screen width and screen height in the main activity. Just copy the below codes and paste it on your main activity.class.
1 2 3 4 | val dm = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(dm)
Constants.SCREEN_WIDTH = dm.widthPixels
Constants.SCREEN_HEIGHT = dm.heightPixels
|
Create a Class
Create a Kotlin class, Name it "Obstacle". In the obstacle class, we stored the obstacle height, width, and player gap. In the obstacle, we describe the two rectangles, which intersects each another. And In the next article, I will draw obstacles on the surface of the screen. Copy the below codes and paste it on your obstacle.class
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 | class Obstacle(rectHeight :Int,private val color:Int,startX:Int,startY:Int,playerGap:Int):GameObject { val rectangle:Rect private val rectangle2:Rect init{ rectangle = Rect(0,startY,startX,startY + rectHeight) rectangle2 = Rect(startX+ playerGap,startY,Constants.SCREEN_WIDTH,startY+rectHeight) } fun playerCollide(player:RectPlayer):Boolean { return Rect.intersects(rectangle,player.rectangle) || Rect.intersects(rectangle2,player.rectangle) } override fun update() { } override fun draw(canvas: Canvas) { val paint = Paint() paint.color = color canvas.drawRect(rectangle,paint) canvas.drawRect(rectangle2,paint) } } |
Remove the Action Bar
Click on the res folder.
Then, click on the values folder.
After, that click on the styles.xml
Now, change the name from "DarkActionBar" to "NoActionBar".
Then, click on the values folder.
After, that click on the styles.xml
Now, change the name from "DarkActionBar" to "NoActionBar".
Conclusion
So, In this article, we have created the obstacle height, width, dimension, and the player gap. In the next article, I will draw obstacles on the surface of the screen. I hope you found this article helpful. If you like this article then, visit again. Thank you.
Comments
Post a Comment