使用加速度计进行滚球运动

时间:2015-11-01 22:13:57

标签: unity3d accelerometer

我正在使用Unity 5.1.1f1中的Android迷宫游戏,我在使用加速度计控制球时遇到了麻烦。一开始我尝试了:

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);
    }   
}

但是球并没有像它应该的那样移动。然后我尝试了另一种方法。但我的球仍然没有向右移动。看起来有时很难向左/向右/向前/向后移动,也有可能我的球会向相反方向旋转。

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);
    }       
}

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

我在另一个SO问题中回答了这个问题:Unity 3D realistic accelerometer control - 你在那里有两种控制变体,只需复制你认为合适的那种。

如果您遇到更多问题,请询问。