动态场景中的力反馈教程
本指南以基础力反馈教程为基础,详细讲解了如何在 Unity 中模拟动态交互,使用户能够感受到来自移动物体的力反馈。 该场景突显了力反馈需要高刷新率,其刷新率远高于 Unity 中视觉渲染的典型刷新率。
导言
为了获得令人信服的触觉体验,特别是在动态场景中,必须以高于1kHz的频率进行计算。 这与游戏通常约60Hz的更新循环形成了鲜明对比。 挑战在于如何在与游戏主循环并行处理这些高频更新的同时,确保线程间的数据交换安全可靠,从而维持一致且精准的力反馈。
基础力反馈配置的扩展
从……现场开始 基础力反馈教程. 为了实现动态行为,我们将调整该脚本 SphereForceFeedback 以便它能对球体的运动作出反应,并模拟与移动物体之间的相互作用。
主要修改内容
- 物体的动态移动:实现一段逻辑代码,根据用户的输入或预定义的移动模式,更新 Sphere 物体的位置和速度。
- 线程间安全的数据交换 : 请使用一个
ReaderWriterLockSlim用于管理主线程与触觉线程之间对共享数据的并发访问。 - 力计算的调整 : 修改该方法
SphereForceFeedback.ForceCalculation为了考虑球体速度,从而提供一种既基于位置又基于运动的、真实的反馈。
动态交互
要模拟球体的运动,您可以选择在该方法中手动更新其位置 Update,或者使用一个独立的组件,该组件根据键盘输入或其他交互来控制其移动。
在此示例中,我们将重命名该对象 球体 en 移动球 并添加该组件 MovingObject 示例中提供的 教程.
改编自 ForceCalculation 为了运动
现在,在计算力反馈时,必须将“移动球”(Moving Ball)的运动速度纳入考量,并根据交互的位置和速度来调整力的大小。 这能带来更细腻、更真实的触觉体验,从而反映出交互的动态特性。
- 添加方法参数
Vector3otherVelocity - 替换
force -= cursorVelocity * dampingparforce -= (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在写锁的保护下更新场景数据。 这确保了当一个线程正在更新数据时,其他线程无法进行读写操作,从而避免了竞争条件并保证了一致性。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,在多个示例中用于通过键盘按键控制所连接的游戏对象的移动。
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);
}
}
}