gpt4 book ai didi

android - android方向传感器的替代品是什么?

转载 作者:IT老高 更新时间:2023-10-28 23:38:49 25 4
gpt4 key购买 nike

您好,我正在为 Android 开发一款 3D 游戏。

我目前正在尝试在我的游戏中添加一个传感器,以允许玩家倾斜 android 作为其控件。

理想情况下,我想使用 ORIENTATION 传感器,但我注意到它已被弃用。有谁知道如何在 android 中检测倾斜并且不使用这个传感器?

最佳答案

没有实际的“方向”传感器 - 这实际上是(曾经)一个复合传感器,由加速度计和磁强计组合生成。

来自 http://developer.android.com/reference/android/hardware/SensorEvent.html

“此传感器类型由于遗留原因而存在,请使用 getRotationMatrix()remapCoordinateSystem()getOrientation() 来计算这些值。”

public class OrientationTestActivity extends Activity implements SensorEventListener
{
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mMagnetometer;

private float[] mLastAccelerometer = new float[3];
private float[] mLastMagnetometer = new float[3];
private boolean mLastAccelerometerSet = false;
private boolean mLastMagnetometerSet = false;

private float[] mR = new float[9];
private float[] mOrientation = new float[3];

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}

protected void onResume() {
super.onResume();
mLastAccelerometerSet = false;
mLastMagnetometerSet = false;
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
}

protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
}

@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor == mAccelerometer) {
System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
mLastAccelerometerSet = true;
} else if (event.sensor == mMagnetometer) {
System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
mLastMagnetometerSet = true;
}
if (mLastAccelerometerSet && mLastMagnetometerSet) {
SensorManager.getRotationMatrix(mR, null, mLastAccelerometer, mLastMagnetometer);
SensorManager.getOrientation(mR, mOrientation);
Log.i("OrientationTestActivity", String.format("Orientation: %f, %f, %f",
mOrientation[0], mOrientation[1], mOrientation[2]));
}
}
}

关于android - android方向传感器的替代品是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10291322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com