How to Use Accelerometer to Move Object by Tilting Phone?
Hey, I'm working as part of a Hackathon. We are trying to make an iOS app for blind and visually impaired people. There are no graphics and your phone acts as a controller for the "rocket suit" that they player is in. We are using Unity to make a level to traverse. When the phone tilts forward, the player(which is just a sphere) should roll forward. The same for all the other directions. There are going to be a lot of audio cues as well.
Originally, we used the Unity documentation to build our accelerometer script, but that made the sphere too difficult to control. We tried to write our own. The link below is that code.
See my accelerometer controller
We are also using two other scripts. This first one is to control the sphere with just arrow keys in testing. We uncheck that when we run the game on a phone. Sphere Controller
The third one just links the camera to the sphere. The forums wouldn't let me post another link, but I don't think that is causing any problems.
The problem is that when the app is run on an iPhone, the game loads but nothing happens when the phone is tilted.
Please let us know as soon as possible if you know anything. We would really appreciate any help! The project is due tomorrow. Thanks!
Answer by ben-rasooli · Apr 24, 2016 at 05:51 AM
Simply add this script to your sphere or whichever object needs to use the accelerometer as a moving force:
using UnityEngine;
[RequireComponent (typeof (Rigidbody))]
public class MoveController : MonoBehaviour {
float speed = 10F;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
Vector3 acc = Input.acceleration;
rb.AddForce(acc.x * speed, 0, acc.y * speed);
}
}
Here, I'm using rigidbody to move the sphere, but you can also use transform.Translate()
if you wish. The idea is just to read the accelerometer x, y and z values and feed them to your method.
Thanks man! This really helps me out a lot! God bless : )
Your answer
Follow this Question
Related Questions
How do I catch a low memory warning from iphone in Unity? 1 Answer
Is it possible to access the native step-counter on mobile platforms. 2 Answers
Unity Hanging when Changing a Vector3.x 2 Answers
How to play animation depending on distance ?? (Video) 0 Answers
Trying to Generate Different Random Values for Position of Game Object Instances [C#] 1 Answer