Nami
Nami

Reputation: 1

Use Accelerometer for Roll-a-ball Movement

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:

public class PlayerController : MonoBehaviour {

    public GameObject sphere;
    public Camera camera;
    public float speed=200;

    private Rigidbody myRigidBody;

    void Start()
    {
        myRigidBody = gameObject.GetComponent<Rigidbody> ();
    }


    void FixedUpdate() 
    {
        float moveH = Input.acceleration.x;
        float moveV = -Input.acceleration.z;

        Vector3 move = new Vector3 (moveH, 0.0f, moveV);
        myRigidBody.AddForce (move * speed*Time.deltaTime);
    }   
}

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.

public class PlayerController : MonoBehaviour {


    public float speedAc = 10;

    //accelerometer
    private Vector3 zeroAc;
    private Vector3 curAc;
    private float sensH = 10;
    private float sensV = 10;
    private float smooth = 0.5f;
    private float GetAxisH = 0;
    private float GetAxisV = 0;

    // Use this for initialization
    void Start () {

        ResetAxes();
    }

    //accelerometer
    void ResetAxes(){
        zeroAc = Input.acceleration;
        curAc = Vector3.zero;
    }

    void FixedUpdate () {

        curAc = Vector3.Lerp(curAc, Input.acceleration-zeroAc, Time.deltaTime/smooth);

        GetAxisH = Mathf.Clamp(curAc.x * sensH, -1, 1);
        GetAxisV = Mathf.Clamp(-curAc.z * sensV, -1, 1);

        Vector3 movement = new Vector3 (GetAxisH, 0.0f, GetAxisV);
        GetComponent<Rigidbody>().AddForce(movement * speedAc);
    }       
}

Can someone help me, please?

Upvotes: 0

Views: 1885

Answers (1)

Krzysztof Bociurko
Krzysztof Bociurko

Reputation: 4662

I have answered this one in another SO question: Unity 3D realistic accelerometer control - you've got two variants of control there, just copy the one you find fit.

If you're having more problems, ask.

Upvotes: 1

Related Questions