-1

I'm trying to develop an app that can detect car acceleration, braking and cornering speed. I need to detect device acceleration. Is that acceleration high or low?. Like flo app on Google Play.

I'm using gyroscope and I need to get highest value for user acceleration (x, y, z axises) from gyroscope. Values of x, y and z are changing every frame. I need to achieve highest value of this 3 axis for later use.

Now my current code looks like this

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

Thanks for any help

1 Answers1

0

Use Time.deltaTime; to do a timer then store Input.gyro.userAcceleration to a temporary Vector3 variable and compare it later on with a new value from the Gyro in the next frame. If the new value is > the old vector3 value, overwrite the old value. When timer is up, you can use the old values as the highest values.

 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);
        }
    }
Programmer
  • 121,791
  • 22
  • 236
  • 328