unity获取设备的重力
1.调用API Input.acceleration方法
void Update(){
Vector3 playerMoveDir=Vector3.zero;
playerMoveDir.x= Input.acceleration.x;
playerMoveDir.y= Input.acceleration.y;
transform.Rotate(playerMoveDir * 70 * Time.deltaTime);
}
这样就可以实现使用重力感应来控制物体的选择
2.初始化重力感应的方向(校正)
private Vector3 playerMoveDir;
Matrix4x4 baseMatrix = Matrix4x4.identity;
private Vector3 testxuanzhuan = Vector3.forward;
private void FixedUpdate()
{
playerMoveDir.x = AdjustedAccelerometer.y;
playerMoveDir.y = AdjustedAccelerometer.x;
transform.Rotate(playerMoveDir * 70 * Time.deltaTime);
}
void CalibrateAcceleration()
{
Quaternion rotate = Quaternion.FromToRotation(new Vector3(0,0,-1), Input.acceleration);
Matrix4x4 matrix = Matrix4x4.TRS(Vector3.zero, rotate, new Vector3(1.0f, 1.0f, 1.0f));
this.baseMatrix = matrix.inverse;
}
public Vector3 AdjustedAccelerometer
{
get
{
return this.baseMatrix.MultiplyVector(Input.acceleration);
}
}
这样就可以实现校准了
|