동적 씬에서의 포스 피드백 튜토리얼
기본 포스 피드백 튜토리얼을 바탕으로, 이 가이드에서는 Unity 내에서 동적 상호작용을 시뮬레이션하여 사용자가 움직이는 객체로부터 포스 피드백을 느낄 수 있도록 하는 방법을 소개합니다. 이 시나리오는 햅틱 피드백에 고주파 업데이트가 필요함을 보여 주며, 이는 Unity에서 시각 렌더링을 위한 일반적인 업데이트 빈도보다 훨씬 높습니다.
소개
특히 동적 씬에서 설득력 있는 햅틱 경험을 제공하려면 1kHz 이상의 주파수로 계산을 수행하는 것이 매우 중요합니다. 이는 보통 약 60Hz로 동작하는 일반적인 게임 업데이트 루프와 극명하게 대조됩니다. 과제는 이러한 고주파 업데이트를 메인 게임 루프와 함께 관리하고, 일관되고 정확한 포스 피드백을 유지하기 위해 스레드 안전한 데이터 교환을 보장하는 데 있습니다.
기본 포스 피드백 설정 확장하기
기본 포스 피드백 튜토리얼의 씬 설정으로 시작하십시오. 동적 동작을 구현하기 위해 SphereForceFeedback 스크립트를 수정하여, 구체의 움직임에 반응하고 동적으로 움직이는 객체와의 상호작용을 시뮬레이션하도록 하겠습니다.
주요 수정 사항
- 동적 객체 이동: 사용자 입력 또는 사전 정의된 움직임 패턴을 기반으로 Sphere의 위치와 속도를 업데이트하는 로직을 포함합니다.
- 스레드 안전 데이터 교환:
ReaderWriterLockSlim을 사용하여 메인 스레드와 햅틱 스레드 간에 공유되는 데이터에 대한 동시 접근을 관리합니다. - 힘 계산 조정:
SphereForceFeedback.ForceCalculation메서드를 수정하여 구체의 속도를 고려하도록 하고, 위치와 움직임 모두를 기반으로 현실감 있는 피드백을 제공합니다.
동적 상호작용
움직이는 구체를 시뮬레이션하려면 Update 메서드에서 위치를 수동으로 업데이트하거나, 키보드 입력 또는 기타 상호작용을 기반으로 움직임을 제어하는 별도의 컴포넌트를 사용할 수 있습니다.
이 예제에서는 Sphere 게임 오브젝트의 이름을 Moving Ball로 변경하고, Tutorials 샘플에 포함된 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 샘플에서 가져올 수 있습니다.
Tutorial 샘플에는 여러 예제에서 키보드 입력으로 게임 오브젝트의 움직임을 제어하는 데 사용되는
MovableObject스크립트가 포함되어 있습니다.
SphereForceFeedback.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);
}
}
}