動的なシーンにおけるフォースフィードバックのチュートリアル
基本的なフォースフィードバックのチュートリアルを基に、このガイドでは、Unity内で動的な相互作用をシミュレートし、ユーザーが動くオブジェクトからフォースフィードバックを感じられるようにする方法について紹介します。 このシナリオは、ハプティックフィードバックには高周波の更新が必要であることを示しており、その更新頻度はUnityにおける視覚レンダリングの一般的な更新頻度よりもはるかに高いものです。
はじめに
特にダイナミックなシーンにおいて説得力のあるハプティック体験を提供するには、1kHz以上の周波数で計算を行うことが極めて重要です。 これは、通常約60Hzで動作する一般的なゲームの更新ループとは著しい対照をなしています。 課題は、こうした高周波数の更新をメインのゲームループと並行して管理し、一貫性があり正確なフォースフィードバックを維持するために、スレッドセーフなデータ交換を確保することにあります。
基本フォースフィードバック設定の拡張
基本的なフォースフィードバック チュートリアルのシーン設定から始めてください。動的な動作を実装するために SphereForceFeedback スクリプトを修正し、球体の動きに反応して動的に動くオブジェクトとの相互作用をシミュレートできるようにします。
主な修正点
- 動的なオブジェクトの移動:ユーザー入力またはあらかじめ定義された移動パターンに基づいて、Sphereの位置と速度を更新するロジックが含まれています。
- スレッドセーフなデータ交換:
ReaderWriterLockSlimを使用して、メインスレッドとハプティックスレッドの間で共有されるデータへの同時アクセスを管理します。 - 力の計算の調整:
SphereForceFeedback.ForceCalculationメソッドを修正して球体の速度を考慮するようにし、位置と動きの両方に基づいて、リアルなフィードバックを提供します。
動的相互作用
動く球体をシミュレーションするには Update メソッド内で位置を手動で更新したり、キーボード入力やその他の操作に基づいて動きを制御する別のコンポーネントを使用したりすることができます。
この例では、 スフィア ゲームオブジェクトの名前を ムービング・ボールに変更し、 チュートリアル サンプルに含まれる MovingObject コンポーネントを追加します。
動きに合わせて ForceCalculation 調整
これからは、力フィードバックの計算において「Moving Ball」の速度を考慮し、相互作用の位置と速度の両方に基づいて力を調整する必要があります。 これにより、相互作用の動的な特性を反映した、より繊細でリアルなハプティック感覚を提供することが可能になります。
Vector3タイプのotherVelocityメソッドの引数を追加してください。force -= cursorVelocity * dampingをforce -= (cursorVelocity - otherVelocity) * dampingに変更してください。
private Vector3 ForceCalculation(Vector3 cursorPosition, Vector3 cursorVelocity, float cursorRadius,
Vector3 otherPosition, Vector3 otherVelocity, float otherRadius)
{
var force = Vector3.zero;
var distanceVector = cursorPosition - otherPosition;
var distance = distanceVector.magnitude;
var penetration = otherRadius + cursorRadius - distance;
if (penetration > 0)
{
// Normalize the distance vector to get the direction of the force
var normal = distanceVector.normalized;
// Calculate the force based on penetration
force = normal * penetration * stiffness;
// Calculate the relative velocity
var relativeVelocity = cursorVelocity - otherVelocity;
// Apply damping based on the relative velocity
force -= relativeVelocity * damping;
}
return force;
}
スレッドセーフなデータ交換
オブジェクトが動き、相互作用するリアルタイムの動的なシーンでは、同時アクセスによるデータの破損を招くことなく、ハプティックフィードバックの計算が常に最新のデータに基づいて行われるようにすることが極めて重要です。 まさにこのような場面において、スレッドセーフなデータ交換が不可欠となります。
スレッドセーフなデータ交換の核心となる概念
- スレッドセーフな仕組み:
ReaderWriterLockSlimを使用して、同時データアクセスを管理します。これにより、複数の読み取り操作や単一の書き込み操作が可能となり、データの整合性が保証されます。 - データの読み取りと書き込み:
- 読み取り:ハプティックスレッドは、読み取りロック状態においてオブジェクトの位置と速度を読み取りますが、この過程でデータの更新を妨げることはありません。
- 書き込み:メインスレッドによるオブジェクトデータの更新は書き込みロック状態で行われるため、同時に発生する読み取りや書き込みによってデータの状態の一貫性が失われるのを防ぎます。
Unityでの実装
-
シーンデータ用構造体:スレッドセーフな処理を容易にするため、シーンに関連する必要なすべてのデータを格納する構造体を定義します。 この構造体には、Moving Ballとカーソルのそれぞれの位置および速度、ならびに半径が含まれます。 このデータ構造は、スレッドセーフなデータ交換の基盤となります。
private struct SceneData{public Vector3 ballPosition;public Vector3 ballVelocity;public float ballRadius;public float cursorRadius;}private SceneData _cachedSceneData; -
ロック解除: シーンデータへのアクセスを管理するために
ReaderWriterLockSlimインスタンスを初期化します。 このロックにより、複数のスレッドが同時にデータを読み取ったり、単一のスレッドが書き込みのためにデータを排他的にロックしたりすることができるため、並行処理中もデータの整合性が保証されます。private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); -
書き込みロックを利用したキャッシュへの書き込み:
SaveSceneDataこのメソッドは、書き込みロックが有効な状態でシーンデータを更新します。 これにより、あるスレッドがデータを更新している間は、他のどのスレッドもそのデータを読み書きできなくなるため、データ競合を防ぎ、一貫性を確保します。private void SaveSceneData(){_cacheLock.EnterWriteLock();try{var t = transform;_cachedSceneData.ballPosition = t.position;_cachedSceneData.ballRadius = t.lossyScale.x / 2f;_cachedSceneData.cursorRadius = inverse3.Cursor.Radius;_cachedSceneData.ballVelocity = _movableObject.Velocity;}finally{_cacheLock.ExitWriteLock();}} -
読み取りロックを利用したキャッシュの読み取り:
GetSceneDataこのメソッドは、読み取りロック内でシーンデータを取得します。 これにより、複数のスレッドが書き込み操作を妨げることなく、データを同時に安全に読み取ることができ、ハプティックフィードバックの計算が最新のシーンデータに基づいて行われることが保証されます。private SceneData GetSceneData(){_cacheLock.EnterReadLock();try{return _cachedSceneData;}finally{_cacheLock.ExitReadLock();}} -
メインスレッドでのデータ更新:
FixedUpdateこのメソッドは、メインスレッドでシーンデータを定期的に更新するために使用されます。 これにより、ハプティックフィードバックの計算が最新のデータにアクセスできるようになり、シーンの動的な特性を反映できるようになります。private void FixedUpdate(){SaveSceneData();} -
スレッドセーフなデータを用いた力計算の適用:
OnDeviceStateChangedコールバックでは、スレッドセーフなメソッドを通じて取得した最新のシーンデータを使用して、力の計算を行います。これにより、力フィードバックが正確であり、シーン内の動的な相互作用に敏感に反応するよう保証されます。var sceneData = GetSceneData();var force = ForceCalculation(device.CursorLocalPosition, device.CursorLocalVelocity, sceneData.cursorRadius,sceneData.ballPosition, sceneData.ballVelocity, sceneData.ballRadius);
ゲームプレイ体験
このスクリプトの改良により、シーン内で能動的に動く球体とインタラクションできるようになりました。 ハプティックフィードバックは球体の軌道に合わせて動的に調整され、より没入感があり、触覚的に豊かな体験を提供します。

ソースファイル
この例のシーン全体および関連ファイルは、Unity パッケージマネージャーの「Tutorials」サンプルから入手できます。
チュートリアル このサンプルには、さまざまな例で、キーボード入力を使ってゲームオブジェクトの動きを制御するために使用される
MovableObjectスクリプトが含まれています。
スフィアフォースフィードバック.cs
/*
* Copyright 2024 Haply Robotics Inc. All rights reserved.
*/
using System.Threading;
using Haply.Inverse.DeviceControllers;
using Haply.Inverse.DeviceData;
using Haply.Samples.Tutorials.Utils;
using UnityEngine;
namespace Haply.Samples.Tutorials._4A_DynamicForceFeedback
{
public class SphereForceFeedback : MonoBehaviour
{
// must assign in inspector
public Inverse3Controller inverse3;
[Range(0, 800)]
// Stiffness of the force feedback.
public float stiffness = 500f;
[Range(0, 3)]
public float damping = 1f;
#region Thread-safe cached data
/// <summary>
/// Represents scene data that can be updated in the Update() call.
/// </summary>
private struct SceneData
{
public Vector3 ballPosition;
public Vector3 ballVelocity;
public float ballRadius;
public float cursorRadius;
}
/// <summary>
/// Cached version of the scene data.
/// </summary>
private SceneData _cachedSceneData;
private MovableObject _movableObject;
/// <summary>
/// Lock to ensure thread safety when reading or writing to the cache.
/// </summary>
private readonly ReaderWriterLockSlim _cacheLock = new();
/// <summary>
/// Safely reads the cached data.
/// </summary>
/// <returns>The cached scene data.</returns>
private SceneData GetSceneData()
{
_cacheLock.EnterReadLock();
try
{
return _cachedSceneData;
}
finally
{
_cacheLock.ExitReadLock();
}
}
/// <summary>
/// Safely updates the cached data.
/// </summary>
private void SaveSceneData()
{
_cacheLock.EnterWriteLock();
try
{
var t = transform;
_cachedSceneData.ballPosition = t.position;
_cachedSceneData.ballRadius = t.lossyScale.x / 2f;
_cachedSceneData.cursorRadius = inverse3.Cursor.Radius;
_cachedSceneData.ballVelocity = _movableObject.Velocity;
}
finally
{
_cacheLock.ExitWriteLock();
}
}
#endregion
/// <summary>
/// Saves the initial scene data cache.
/// </summary>
private void Start()
{
inverse3 ??= FindFirstObjectByType<Inverse3Controller>();
inverse3.Ready.AddListener((device, args) => SaveSceneData());
_movableObject = GetComponent<MovableObject>();
}
/// <summary>
/// Update scene data cache.
/// </summary>
private void FixedUpdate()
{
if (inverse3.IsReady)
{
SaveSceneData();
}
}
/// <summary>
/// Subscribes to the DeviceStateChanged event.
/// </summary>
private void OnEnable()
{
inverse3.DeviceStateChanged += OnDeviceStateChanged;
}
/// <summary>
/// Unsubscribes from the DeviceStateChanged event.
/// </summary>
private void OnDisable()
{
inverse3.DeviceStateChanged -= OnDeviceStateChanged;
inverse3.Release();
}
/// <summary>
/// Calculates the force based on the cursor's position and another sphere position.
/// </summary>
/// <param name="cursorPosition">The position of the cursor.</param>
/// <param name="cursorVelocity">The velocity of the cursor.</param>
/// <param name="cursorRadius">The radius of the cursor.</param>
/// <param name="otherPosition">The position of the other sphere (e.g., ball).</param>
/// <param name="otherVelocity">The velocity of the other sphere (e.g., ball).</param>
/// <param name="otherRadius">The radius of the other sphere.</param>
/// <returns>The calculated force vector.</returns>
private Vector3 ForceCalculation(Vector3 cursorPosition, Vector3 cursorVelocity, float cursorRadius,
Vector3 otherPosition, Vector3 otherVelocity, float otherRadius)
{
var force = Vector3.zero;
var distanceVector = cursorPosition - otherPosition;
var distance = distanceVector.magnitude;
var penetration = otherRadius + cursorRadius - distance;
if (penetration > 0)
{
// Normalize the distance vector to get the direction of the force
var normal = distanceVector.normalized;
// Calculate the force based on penetration
force = normal * penetration * stiffness;
// Calculate the relative velocity
var relativeVelocity = cursorVelocity - otherVelocity;
// Apply damping based on the relative velocity
force -= relativeVelocity * damping;
}
return force;
}
/// <summary>
/// Event handler that calculates and send the force to the device when the cursor's position changes.
/// </summary>
/// <param name="sender">The Inverse3 data object.</param>
/// <param name="args">The event arguments containing the device data.</param>
private void OnDeviceStateChanged(object sender, Inverse3EventArgs args)
{
var inverse3 = args.DeviceController;
var sceneData = GetSceneData();
// Calculate the moving ball force.
var force = ForceCalculation(inverse3.CursorLocalPosition, inverse3.CursorLocalVelocity, sceneData.cursorRadius,
sceneData.ballPosition, sceneData.ballVelocity, sceneData.ballRadius);
// Apply the force to the cursor.
inverse3.SetCursorLocalForce(force);
}
}
}