0

我有一個應用程序,它顯示用加速度計和磁力計計算出的x,y,z方向值。但是當我從肖像換成風景時,我沒有得到相同的X值。我tryed,帶有旋轉矢量來實現,但我的設備沒有旋轉矢量傳感器:■用設備方向計算X方向值

這裏是我的代碼來計算X,Y,Z值:

@Override 
public void onSensorChanged(SensorEvent event) { 
    // TODO Auto-generated method stub 
    float x, y, z; 
    String s1 = "stringX", s2 = "stringY", s3 = "stringZ"; 
    // Mettre à jour la valeur de l'accéléromètre et du champ magnétique 
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
     acceleromterVector=event.values; 
    } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { 
     magneticVector=event.values; 
    } 
    // Demander au sensorManager la matrice de Rotation (resultMatrix) 
    SensorManager.getRotationMatrix(resultMatrix, null, acceleromterVector, magneticVector); 
    // Demander au SensorManager le vecteur d'orientation associé (values) 
    SensorManager.getOrientation(resultMatrix, values); 
    // l'azimuth 
    x = (float) Math.toDegrees(values[0]); 
    // le pitch 
    y = (float) Math.toDegrees(values[1]); 
    // le roll 
    z = (float) Math.toDegrees(values[2]); 


    s1 = "X :" + x; 
    s2 = "Y :" + y;   
    s3 = "Z :" + z; 

    tvx.setText(s1); 
    tvy.setText(s2); 
    tvz.setText(s3); 

    updateOrientation(x); 
} 

謝謝你們。

回答

0

傳感器值始終相對於默認方向,因此您需要考慮遠離默認方向的旋轉。要做到這一點,請使用以下內容:

int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); 
float screen_adjustment = 0; 
switch(rotation) { 
    case Surface.ROTATION_0: screen_adjustment =   0;   break; 
    case Surface.ROTATION_90: screen_adjustment = (float)Math.PI/2; break; 
    case Surface.ROTATION_180: screen_adjustment = (float)Math.PI; break; 
    case Surface.ROTATION_270: screen_adjustment = 3*(float)Math.PI/2; break; 
} 

調整azimith。有關完整的示例,請參閱the code that I posted in my answer here

+0

你完全的例子看起來很有趣,但有點難。 如果我處理這個screen_adjustment,我必須做方位角+屏幕調整才能獲得正確的方位角值? – Eydolol

+0

事實上,只要您的設備躺在桌子上靠近平面,我會希望方位角+ screen_adjustment爲您提供正確的方位角。當設備直立時,來自'SensorManager.getOrientation'的方位開始行爲異常,這就是我的例子。 – Stochastically

+0

這對我來說不合邏輯的,如果我加上1.5(這是PI/2)的調整值,我對X有85的基本值,它不會改變我的方向,從0-> 360°移動。我希望你能理解我:x – Eydolol