2016-04-05 124 views
-1

我試圖開發一款可以檢測汽車加速,制動和轉彎速度的應用程序。我需要檢測設備加速。這個加速度是高還是低?像Google Play上的flo應用一樣。Unity3D - 如何從Input.gyro獲得最高加速值

我正在使用陀螺儀,我需要從陀螺儀獲得用戶加速度(x,y,z軸)的最高值。 x,y和z的值正在改變每一幀。我需要獲得這個3軸的最高價值供以後使用。

現在我當前的代碼看起來像這樣

using UnityEngine; 
using System.Collections; 
using UnityEngine.UI; 

public class NewBehaviourScript : MonoBehaviour 
{ 
public Text x, y, z; 

void Start() 
{ 
    Input.gyro.enabled = true; 
} 

void Update() 
{ 
    x.text = Mathf.Abs(Input.gyro.userAcceleration.x).ToString(); 
    y.text = Mathf.Abs(Input.gyro.userAcceleration.y).ToString(); 
    z.text = Mathf.Abs(Input.gyro.userAcceleration.z).ToString(); 
} 
} 

感謝所有幫助

+0

你的問題很混亂....你想檢查哪個軸大於3個?解釋更多關於你想要做什麼...... – Programmer

+0

不,我想獲得每個軸的最高值 –

+0

獲得x,y,z的最高值......這是沒有意義的。如果您確實需要幫助,請修改您的問題,然後添加您的最高價值以及您要存檔的內容。 – Programmer

回答

1

使用Time.deltaTime;做一個計時器,然後存儲Input.gyro.userAcceleration到一個臨時Vector3變量和比較後來在一個新的來自下一幀的陀螺儀的值。如果新值爲>舊的vector3值,則將覆蓋的舊值。計時器啓動時,可以使用舊值作爲最高值。

void Start() 
{ 
    Input.gyro.enabled = true; 
} 

bool firstRun = true; 
float counter = 0; 
float calcTime = 1; //Find highest gyro value every 1 seconds 
Vector3 oldGyroValue = Vector3.zero; 
Vector3 highestGyroValue = Vector3.zero; 

    void Update() 
    { 
     gyroFrame(); 
    } 

    void gyroFrame() 
    { 

     if (firstRun) 
     { 
      firstRun = false; //Set to false so that this if statement wont run again 
      oldGyroValue = Input.gyro.userAcceleration; 
      counter += Time.deltaTime; //Increment the timer to reach calcTime 
      return; //Exit if first run because there is no old value to compare with the new gyro value 
     } 

     //Check if we have not reached the calcTime seconds 
     if (counter <= calcTime) 
     { 
      Vector3 tempVector = Input.gyro.userAcceleration; 
      //Check if we have to Update X, Y, Z 
      if (tempVector.x > oldGyroValue.x) 
      { 
       oldGyroValue.x = tempVector.x; 
      } 

      if (tempVector.y > oldGyroValue.y) 
      { 
       oldGyroValue.y = tempVector.y; 
      } 

      if (tempVector.z > oldGyroValue.z) 
      { 
       oldGyroValue.z = tempVector.z; 
      } 
      counter += Time.deltaTime; 
     } 

     //We have reached the end of timer. Reset counter then get the highest value 
     else 
     { 
      counter = 0; 
      highestGyroValue = oldGyroValue; 
      Debug.Log("The Highest Values for X: " + highestGyroValue.x + " Y: " + highestGyroValue.y + 
       " Z: " + highestGyroValue.z); 
     } 
    }