동적인 장면에서의 포스 피드백: 튜토리얼
포스 피드백에 대한 기초 튜토리얼을 바탕으로, 이 가이드에서는 사용자가 움직이는 오브젝트로부터 포스 피드백을 느낄 수 있도록 Unity 내에서 동적인 상호작용을 시뮬레이션하는 방법을 설명합니다. 이 시나리오는 햅틱 피드백을 구현하려면 Unity의 일반적인 시각적 렌더링 업데이트 빈도를 훨씬 뛰어넘는 고주파수 업데이트가 필요함을 보여줍니다.
서론
특히 역동적인 장면에서 설득력 있는 햅틱 경험을 제공하려면 1kHz 이상의 주파수로 계산을 수행하는 것이 매우 중요합니다. 이는 약 60Hz로 작동하는 일반적인 게임 업데이트 루프와 극명한 대조를 이룹니다. 여기서 과제는 이러한 고주파수 업데이트를 게임의 메인 루프와 병렬로 처리하고, 일관되고 정밀한 포스 피드백을 보장하기 위해 스레드 안전성이 확보된 데이터 교환을 실현하는 데 있습니다.
기본 포스 피드백 설정 확장
다음에서 장면 구성을 시작해 보세요. 포스 피드백 기초 튜토리얼. 동적 동작을 구현하기 위해 스크립트를 수정합니다. SphereForceFeedback ...하여 공의 움직임에 반응하고, 동적으로 움직이는 물체와의 상호작용을 시뮬레이션합니다.
주요 변경 사항
- 동적 객체의 움직임: 사용자 입력이나 미리 정의된 움직임 패턴에 따라 공의 위치와 속도를 업데이트하는 로직을 통합하십시오.
- 보안성이 강화된 데이터 교환: 다음을 사용하십시오.
ReaderWriterLockSlim, 메인 스레드와 햅틱 스레드 간에 공유되는 데이터에 대한 동시 액세스를 관리하기 위해. - 힘 계산의 조정: 메서드를 조정하십시오
SphereForceFeedback.ForceCalculation이로써 공의 속도가 반영되고, 위치와 움직임을 바탕으로 현실감 있는 피드백이 생성되도록 합니다.
동적 상호작용
움직이는 구체를 시뮬레이션하려면, 메서드 내에서 그 위치를 수동으로 설정하거나 Update 업데이트하거나, 키 입력이나 기타 상호작용을 통해 움직임을 제어하는 별도의 컴포넌트를 사용합니다.
이 예제에서는 GameObject의 이름을 구체 에서 움직이는 공 음, 그리고 예시에 있는 것을 추가하면 튜토리얼 포함된 구성 요소 MovingObject hinzu.
다음의 수정: ForceCalculation 운동을 위해
이제 포스 피드백을 계산할 때는 움직이는 공의 속도를 고려해야 하며, 상호작용의 위치와 속도를 모두 바탕으로 힘을 조정해야 합니다. 이를 통해 상호작용의 역동적인 특성을 반영하는, 더욱 세분화되고 현실감 있는 햅틱 감각이 구현됩니다.
- 메서드에 매개변수를 추가하세요
Vector3otherVelocityhinzu - 다음으로 대체하십시오
force -= cursorVelocity * dampingdurchforce -= (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에서의 구현
-
씬 데이터를 위한 구조체: 스레드 안전 작업을 가능하게 하기 위해, 씬에 대한 모든 필수 데이터를 포함하는 구조체를 정의합니다. 이 구조체에는 움직이는 공과 커서의 위치와 속도, 그리고 반지름이 모두 포함됩니다. 이 데이터 구조체는 스레드 안전 데이터 교환의 기반이 됩니다.
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쓰기 잠금 상태에서 장면 데이터를 업데이트합니다. 이를 통해 한 스레드가 데이터를 업데이트하는 동안 다른 스레드가 해당 데이터를 읽거나 쓸 수 없도록 보장합니다. 이는 데이터 경합(Data Races)을 방지하고 일관성을 보장합니다.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();} -
최신 데이터를 활용한 힘 계산 적용: Im Callback
OnDeviceStateChanged스레드 안전 메서드를 통해 가져온 최신 씬 데이터를 바탕으로 힘 계산이 수행됩니다. 이를 통해 힘 피드백이 정밀하게 구현되며, 씬 내의 동적인 상호작용에 반응합니다.var sceneData = GetSceneData();var force = ForceCalculation(device.CursorLocalPosition, device.CursorLocalVelocity, sceneData.cursorRadius,sceneData.ballPosition, sceneData.ballVelocity, sceneData.ballRadius);
게임 체험
이 스크립트 확장 기능을 사용하면 씬 내에서 능동적으로 움직이는 공과 상호작용할 수 있습니다. 햅틱 피드백은 공의 궤적에 따라 동적으로 조정되어, 더욱 강렬하고 촉각적으로 풍부한 경험을 제공합니다.

원본 파일
이 예제의 전체 장면과 관련 파일은 Unity의 패키지 관리자에서 ‘예제 튜토리얼’을 통해 가져올 수 있습니다.
예시 튜토리얼 스크립트에는 다음이 포함되어 있습니다
MovableObject, 이는 여러 예제에서 키보드 입력을 통해 연결된 GameObject의 움직임을 제어하는 데 사용됩니다.
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);
}
}
}