as unity 3d is now available for linux <3 i was playing with it sice then. the first tutorial you will find as a beginner in unity official site is 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 generally in 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 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 force to our player object. if u think in simple physics we added a force to an object which is a multiply 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 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 setup 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. 🙂