Search Unity

Use Accelerometer for Roll-a-ball Movement

Discussion in 'Physics' started by Natasa, Nov 2, 2015.

  1. Natasa

    Natasa

    Joined:
    May 28, 2013
    Posts:
    14
    I'm working on maze game for Android in Unity 5.1.1f1 and I have troubles with controlling my ball with accelerometer. At start I tried:

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    2.  
    3.     public GameObject sphere;
    4.     public Camera camera;
    5.     public float speed=200;
    6.  
    7.     private Rigidbody myRigidBody;
    8.  
    9.     void Start()
    10.     {
    11.         myRigidBody = gameObject.GetComponent<Rigidbody> ();
    12.     }
    13.  
    14.     void FixedUpdate()
    15.     {
    16.         float moveH = Input.acceleration.x;
    17.         float moveV = -Input.acceleration.z;
    18.  
    19.         Vector3 move = new Vector3 (moveH, 0.0f, moveV);
    20.         myRigidBody.AddForce (move * speed*Time.deltaTime);
    21.     }  
    22. }
    23.  
    But the ball is not moving as it should. Then I tried another solution. But my ball still doesn't move right. It seems like it's sometimes hard to move left/right/forward/backward, also it's possible my ball will rotate in the opposite direction.

    Code (CSharp):
    1. public class PlayerController : MonoBehaviour {
    2.  
    3.  
    4.     public float speedAc = 10;
    5.  
    6.     //accelerometer
    7.     private Vector3 zeroAc;
    8.     private Vector3 curAc;
    9.     private float sensH = 10;
    10.     private float sensV = 10;
    11.     private float smooth = 0.5f;
    12.     private float GetAxisH = 0;
    13.     private float GetAxisV = 0;
    14.  
    15.     // Use this for initialization
    16.     void Start () {
    17.  
    18.         ResetAxes();
    19.     }
    20.  
    21.     //accelerometer
    22.     void ResetAxes(){
    23.         zeroAc = Input.acceleration;
    24.         curAc = Vector3.zero;
    25.     }
    26.  
    27.     void FixedUpdate () {
    28.      
    29.         curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);
    30.          
    31.         GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
    32.         GetAxisV = Mathf.Clamp(-curAc.z * sensV, -1, 1);
    33.          
    34.         Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
    35.         GetComponent<Rigidbody>().AddForce(movement * speedAc);
    36.     }      
    37. }
    Can someone help me, please?
     
    Last edited: Nov 2, 2015
  2. Natasa

    Natasa

    Joined:
    May 28, 2013
    Posts:
    14