Skip to main content
 

How to Create a Color Changing Sensor Game in Android Studio with Kotlin



Hello World, Many of us acknowledge about Sensors. Sensors are very significant parts of our Smartphone. There are many types of Sensors. In this article, we will learn "how to create a color changing sensor game in the android studio with kotlin" support.

Lets Learn About Sensors

There are many types of sensors in our smartphone. We can build different types of application with the sensors. For now, we will use the accelerometer. The accelerometer measures the acceleration force in the form of m/sq. And it applies three physical axes(x,y,z) into the device. Its also measure the force of gravity. When we shake or tilt the phone, its detect the motion. If you have studied coordinate in high school, you can easily understand the accelerometer and another sensor as well.

Create a new Android Studio project 


  • Create a new project in Android Studio
  • Name it "Sensor Game".
  • Tick Kotlin support, in your project.





  • Then choose an empty activity, And click finish.


Design the Interface of the Application

Now, we will design the interface of the Application. We will do it on (activity_main.xml).In XML we can design the interface of the application. In our app, we will use TextView and View widget. Then we will come to the coding part. Here we will use Kotlin to code our Application. First of all, Let talk about Kotlin language. Kotlin was developed in 2011. And Kotlin is a JVM language. Also as compared to Java, Kotlin is more robust. There are many features in Kotlin which java does not support. The bonus part of Kotlin is, we can change java codes into Kotlin codes. So, let jump into the XML design.


 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
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relative"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/tvHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:text="@string/app_name"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="40sp" />

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@+id/tvHeader"
        android:background="@color/colorPrimary" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/tvXAxiz"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:padding="10dp"
        android:text="X-Axis"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="18sp" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/tvYAxis"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvXAxiz"
        android:gravity="center"
        android:padding="10dp"
        android:text="Y-Axis"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="18sp" />

    <android.support.v7.widget.AppCompatTextView
        android:id="@+id/tvZAxis"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvYAxis"
        android:gravity="center"
        android:padding="10dp"
        android:text="Z-Axis"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="18sp" />

</RelativeLayout>

Let Write Kotlin Code in Main Activity

In the coding part we will Sensor Event Listener and there are four overrides methods. We use the sensor event listener to receive notification from the sensor manager, wherever the new sensor data is obtained.We use four overrides method when we use sensor event listener,the overrides method are as follows:onAccuracyChanged(),onSensorChanged(),onResume(),onPause().The idea is that, when we shuffled the phone, then the color will be changed. When we shuffled the phone upwards, its change to primary dark and when we shuffled the phone downwards, its change to yellow color. Now we know what to do, let's do some coding in Kotlin.


 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
import android.content.Context
import android.graphics.Color
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), SensorEventListener {

    private var sensorManager: SensorManager? = null
    private var color = false

    override fun onAccuracyChanged(s: Sensor?, i: Int) {
    }

    override fun onSensorChanged(event: SensorEvent?) {
        if (event!!.sensor.type == Sensor.TYPE_ACCELEROMETER) {
            getAccelerometer(event)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
    }

    private fun getAccelerometer(event: SensorEvent) {
        // Movement
        val xVal = event.values[0]
        val yVal = event.values[1]
        val zVal = event.values[2]
        tvXAxiz.text = "X Value: ".plus(xVal.toString())
        tvYAxis.text = "Y Value: ".plus(yVal.toString())
        tvZAxis.text = "Z Value: ".plus(zVal.toString())

        val accelerationSquareRoot = (xVal * xVal + yVal * yVal + zVal * zVal) / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH)

        if (accelerationSquareRoot >= 3) {
            Toast.makeText(this, "Device was shuffled", Toast.LENGTH_SHORT).show()
            if (color) {
                relative.setBackgroundColor(resources.getColor(R.color.colorAccent))
            } else {
                relative.setBackgroundColor(Color.YELLOW)
            }
            color = !color
        }
    }

    override fun onResume() {
        super.onResume()
        sensorManager!!.registerListener(this, sensorManager!!.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL)
    }

    override fun onPause() {
        super.onPause()
        sensorManager!!.unregisterListener(this)
    }
}


Add Colour 

Now add color to the colors.xml file. Which you can open from res, then values folder. Just copy the codes from below and paste it on the color.xml.


1
2
3
4
5
<resources>
    <color name="colorPrimary">#17A589</color>
    <color name="colorPrimaryDark">#117864</color>
    <color name="colorAccent">#1ABC9C</color>
</resources>

Test Application on the Android Phone 

Now, we can test the application on the Android Phone, don't test the application on the emulator. because we will not get a result. Test the app on a real Android phone. You can use temporary APK of the app to test the application or if you want to publish the app on play store, then you want to generate signed APK of the application.



We have successfully created the games. I know this application not look like a game, but from this method, you can create many sensors game. I will publish more article on 2d sensor game in the future. So, stay connected with our website. In this article, we have learned how to implement a sensor event listener and five overrides methods of the sensor event listener. I hope you have like this article. Also feel free to ask a question from me.



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 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 Create an empty project in the android studio. Name your application. Then select the Kotlin support. After that, select the API l

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