As unity 3d is now available for Linux, I was playing with it since then. The first tutorial you will find as a beginner in unity official site is a roll-a-ball game which you can find in here. I assume you have completed this and willing to port this to android or ios which is the main intention of this post.
You can build and run this on pc or mobile devices. But if you try to run this on Android or a mobile device your player object won’t move as you moved it in pc. This is because we want to configure our player object to use accelerometer or gyroscope data from the mobile device as inputs.
What we did on the player controller script is we took the keyboard input of horizontal and vertical axis and created a 3D vector with having 0 as y component. One thing to make a note here is that in general vectors we are considering z-axis as the axis which stands vertically from XY plane which governs up/ down movements. But in unity 3D y-axis is the one which governs up/down movements. From here on I will use the Unity grid system for explanations.
float moveHorizontal= Input.GetAxis("Horizontal"); float moveVertical= Input.GetAxis("Vertical"); Vector3 movement= new Vector3(moveHorizontal, 0.0f, moveVertical); rb.AddForce(movement* speed);
What we did here was first we generated a 3d vector from keyboard inputs for x and z movements. We made y-axis as 0 as we don’t want our player object to move vertically or up/down. Then we add the vector multiplied by a scalar as a force to our player object. If u think in simple physics we added a force to an object which is a multiple of a vector and scaler. Does it ring a bell?? 😛
We created an acceleration vector from keyboard inputs, and multiplied by the mass and add that force to the player object. The more you increase the mass more force is added, so the rate of change of the object’s position will increase.
So the only thing we have to do here is get the acceleration from the mobile device and add it to our acceleration vector. Unity’s interface to the input system provides this natively. You can get the acceleration vector from
Input.acceleration. As we want to make y-axis acceleration zero we can do following.
Vector3 movement= new Vector3(Input.acceleration.x, 0.0f, Input.acceleration.y); rb.AddForce(movement* speed);
Note that here in
Input.acceleration.y provides the linear acceleration of y axis in cartesian grid system. We are all set. Switch build platform to Android and hit build and run. You may need to set up a bundle identifier for the app if you are switching platforms for the first time.
Now you can play the game by tilting your phone. 🙂