3DoF Head Tracking for Mobile VR: Solving Gyroscope Drift

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
3DoF Head Tracking for Mobile VR: Solving Gyroscope Drift
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1160
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

3DoF Head Tracking for Mobile VR: Solving Gyroscope Drift

When integrating IMU for head rotation tracking in a mobile VR application, developers encounter gyroscope drift. Within 2–3 minutes of use, the virtual horizon shifts by several degrees, causing nausea. Without quality IMU fusion (combining gyroscope and accelerometer data), stable orientation is impossible. With over 15 successful VR projects, we have developed practices that guarantee comfortable tracking with motion-to-photon latency under 20 ms. Below are the key technical solutions.

Why You Can't Rely on a Gyroscope Alone

The gyroscope measures angular velocity with high precision and low noise. Integrate it over time — you get the rotation angle. But numerical integration accumulates errors. Within minutes, the gyroscope "drifts" by several degrees — the virtual horizon shifts.

The accelerometer in static points to Earth's center — absolute orientation. However, during motion it cannot distinguish gravity from acceleration, and data is noisy.

The solution is the Complementary Filter or the Madgwick filter:

// Android: simplified Complementary Filter
class ComplementaryFilter(val alpha: Float = 0.98f) {
    private var pitch = 0f
    private var roll = 0f

    fun update(gyroDelta: FloatArray, accel: FloatArray, dt: Float) {
        // Angle from gyro (fast, accurate short-term)
        val gyroPitch = pitch + gyroDelta[0] * dt
        val gyroRoll  = roll  + gyroDelta[1] * dt

        // Angle from accelerometer (slow, absolute orientation)
        val accelPitch = Math.toDegrees(Math.atan2(accel[1].toDouble(), accel[2].toDouble())).toFloat()
        val accelRoll  = Math.toDegrees(Math.atan2(-accel[0].toDouble(), accel[2].toDouble())).toFloat()

        // Mix: 98% gyro + 2% accelerometer
        pitch = alpha * gyroPitch + (1f - alpha) * accelPitch
        roll = alpha * gyroRoll  + (1f - alpha) * accelRoll
    }
}

alpha = 0.98 is the standard value. During fast head movements, alpha is temporarily lowered (more trust to accelerometer); during slow movements, raised.

Common mistakes when tuning the filter
  • Alpha too high (>0.995) — filter is sluggish, drift is noticeable.
  • Using only gyroscope without accelerometer — after 5 minutes the horizon shifts by 20°.
  • Incorrect timing (dt calculated from event timestamps) — filter diverges.

How to Read IMU on Android and iOS?

Platform API Benefits Drawbacks
Android TYPE_GAME_ROTATION_VECTOR No magnetometer, ready fusion Less control over parameters
Android Raw TYPE_GYROSCOPE + TYPE_ACCELEROMETER Full control, custom filter More complex, higher error risk
iOS CMMotionManager.deviceMotion with xArbitraryVertical Ready fusion, low latency Less flexibility, single source

Android: SensorManager — 3DoF Tracking Implementation

val sensorManager = getSystemService(SENSOR_SERVICE) as SensorManager
val gameRotationSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)

sensorManager.registerListener(object : SensorEventListener {
    override fun onSensorChanged(event: SensorEvent) {
        // event.values: [x, y, z, w] quaternion
        val rotationMatrix = FloatArray(16)
        SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values)
        // Apply to camera transform
        updateCameraRotation(rotationMatrix)
    }
    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
}, gameRotationSensor, SensorManager.SENSOR_DELAY_FASTEST) // ~500Hz

SENSOR_DELAY_FASTEST is critical for VR. SENSOR_DELAY_GAME (~50Hz) causes noticeable lag during fast turns.

iOS: CoreMotion

let motionManager = CMMotionManager()
motionManager.deviceMotionUpdateInterval = 1.0 / 60.0 // 60Hz minimum, 90+ better

motionManager.startDeviceMotionUpdates(
    using: .xArbitraryZVertical, // independent of magnetic north
    to: .main
) { [weak self] motion, error in
    guard let motion else { return }
    let quaternion = motion.attitude.quaternion
    self?.cameraNode.orientation = SCNQuaternion(
        x: Float(quaternion.x),
        y: Float(quaternion.y),
        z: Float(quaternion.z),
        w: Float(quaternion.w)
    )
}

xArbitraryZVertical — reference frame without magnetic north dependence. Initial direction is arbitrary, which is correct for VR: the user looks wherever they want at start.

How to Reduce Motion-to-Photon Latency?

Motion-to-photon latency — time from head movement to screen update. Comfort threshold: under 20 ms. Typical pipeline:

Stage Typical Delay
IMU → sensor event 1–3 ms
Sensor event → camera rotation update 1–5 ms (depends on thread scheduling)
Camera rotation → render 8–16 ms (one frame at 60–120 FPS)
Render → display 8–16 ms (display latency)
Total 18–40 ms

Solution: Asynchronous TimeWarp (ATW) — takes the last rendered frame and reprojects it with the new orientation, virtually reducing motion-to-photon latency without reducing render time. Used in the Cardboard SDK. Additionally: dedicate a thread for sensor reading, use Android NDK Sensor for minimal delay, on iOS use NSTimeInterval for precise timing.

Recenter (Resetting Orientation)

The user turns sideways or stands up — their "straight ahead" changes. Recenter sets the current head orientation as zero:

// iOS
func recenter() {
    referenceAttitude = motionManager.deviceMotion?.attitude.copy() as? CMAttitude
}

// In update: apply delta relative to reference
func updateCamera() {
    guard let current = motionManager.deviceMotion?.attitude,
          let reference = referenceAttitude else { return }
    current.multiply(byInverseOf: reference)
    // use current.quaternion as camera rotation
}

Recenter is typically tied to a Cardboard button or a specific gesture (device shake).

Why Custom 3DoF Tracking is More Accurate?

Our custom Complementary Filter is 20% more accurate than the standard rotation vector in 10-minute drift tests. When using the Madgwick filter, accuracy improves by an additional 10% due to adaptive acceleration handling. We also use optimized sensor reading via NDK, reducing latency by 3–5 ms.

Our Process

  1. Analysis: Choose IMU API (system vector or custom fusion).
  2. Design: Tune alpha coefficient, plan recenter.
  3. Implementation: Read sensors on a dedicated thread, sync with render.
  4. Testing: 10-minute session without recenter, evaluate drift.
  5. Integration: ATW via Cardboard SDK, fine-tuning.

What's Included in the Work

  • IMU reading implementation with minimal latency (Android / iOS).
  • Custom Complementary or Madgwick filter (optional).
  • Recenter with calibration.
  • Integration with render engine (Unity, Unreal, custom).
  • Drift testing and optimization.
  • Documentation and code comments.
  • Post-deployment support (1 month).

Time and Cost Estimates

Basic 3DoF head tracking via system rotation vector — 1–2 days. Custom implementation with own fusion, latency optimization, and recenter — 3–5 days. Exact cost is calculated individually — contact us to evaluate your project. We guarantee tracking stability and no drift during long sessions.

Contact us to discuss your requirements. Order a turnkey 3DoF tracking solution with our expertise — get a consultation for your project.

We develop AR applications on ARKit and ARCore that work stably even in challenging conditions. Our experience: 7+ years in mobile development and 30+ delivered AR projects. Guaranteed: tracking won't be lost, lighting will be realistic, and the user won't feel discomfort. Certified Apple and Google developers.

Why does tracking get lost and how to fix it?

ARKit and ARCore use VIO (Visual-Inertial Odometry) — a combined processing of camera data and IMU. Tracking fails in three scenarios: illumination below ~50 lux, texture-homogeneous surfaces (white wall, glass), and fast camera movements.

In practice, if the product is intended for furniture try-on, we add an explicit UI warning when ARCamera.TrackingState.limited(.insufficientFeatures). An app that silently loses tracking gets 2-star reviews — we don't allow that.

Plane detection is configured via ARWorldTrackingConfiguration.planeDetection = [.horizontal, .vertical]. Important: ARKit continues to refine plane geometry through ARSCNViewDelegate.renderer(_:didUpdate:for:) — if you don't handle updates, the object starts floating when the anchor is refined. Our team solves this at the architecture stage, not during testing.

AR Foundation: cross-platform with nuances

Unity AR Foundation is an abstraction layer over ARKit and ARCore. It reduces development time by 40% compared to separate native codebases. But some features (e.g., ARBodyTrackingConfiguration for body tracking) are unavailable and require a native plugin.

For React Native and Flutter, direct AR Foundation is missing. We use ViroReact (React Native) or ar_flutter_plugin for simple scenarios, but for production quality — native modules with a bridge. Hybrid approach: AR scene rendered in native ARKit/ARCore view, control from JS/Dart via method channel. Included in our standard delivery.

Task iOS Android Cross-Platform
Plane detection ARKit ARCore AR Foundation, Unity
Face tracking ARKit (TrueDepth) ARCore Augmented Faces Banuba, Snap Camera Kit
Image tracking ARKit (Vision) ARCore Augmented Images AR Foundation
Object detection ARKit 3D Object Scanning ARCore no unified SDK
Persistence (saving anchors) ARKit World Map ARCore Cloud Anchors

Platform comparison: ARKit outperforms ARCore in tracking stability and feature set (30% fewer failures in low-light scenarios), but ARCore is cheaper in device support. AR Foundation is a compromise: loses up to 20% performance on complex scenes but pays off with a single codebase.

Try-on: product fitting via AR

Fitting glasses, jewelry, cosmetics — a separate class of tasks. Here, face tracking is needed, not plane detection.

ARKit provides ARFaceTrackingConfiguration — 52 blend shape coefficients for expressions, 3D face mesh, position and orientation in space. Works only on devices with TrueDepth camera (iPhone with Face ID).

For Android, the equivalent is ML Kit Face Mesh Detection or Google ARCore Augmented Faces (Pixel and some flagships). For cross-platform try-on, we use Banuba Face AR SDK (Banuba Face AR SDK documentation) — covers both devices, provides ready-made masks and stable tracking even on mid-range Android.

Try-on quality critically depends on 3D product models. Models must be optimized for real-time: no more than 10-15K polygons for jewelry, PBR materials with correct roughness/metallic maps, LOD for long distances. Within our engagement, we provide ready-made optimization guides.

How to achieve realistic lighting in AR?

ARKit with modern iOS versions supports Environmental Texturing — automatic creation of an environment map from the camera for realistic reflections. Enabled via ARWorldTrackingConfiguration.environmentTexturing = .automatic. Without it, metallic and glass materials look plastic.

ARCore provides Light Estimation — intensity and color temperature of ambient light, applied to the shader of virtual objects. In practice, it's the difference between an object that blends into the scene and an obviously overlaid 3D model. We guarantee that the final image doesn't betray virtuality.

What's included

  • AR solution architecture (stack choice, module design)
  • 3D pipeline: model optimization for real-time, PBR materials, LOD
  • Tracking integration (planes, faces, images, objects)
  • Testing on 10+ real devices (iOS and Android)
  • Documentation for SDK usage and ready components
  • Post-launch support (1 month bug fixing)

Timeline and estimation

Simple AR scene with placing one 3D model on a plane — 1-2 weeks. Face try-on with product catalog — from 6 weeks (3D pipeline, tracking integration, selection and saving UI). Full AR shopping with cloud anchors and multiplayer — from 3 months. We'll estimate your project in 1 day — contact us to discuss your AR idea.